反映[]字节的值

kwo*_*lfe 4 reflection go

如何检索此接口的[]字节值?

package main

import (
    "reflect"
)

func byteInterface() interface{} {
    return []byte("foo")
}

func main() {
    //var b []byte
    i := byteInterface()

    switch {
    case reflect.TypeOf(i).Kind() == reflect.Slice && (reflect.TypeOf(i) == reflect.TypeOf([]byte(nil))):

    default:
        panic("should have bytes")
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*per 7

You can use a type assertion for this; no need to use the reflect package:

package main

func byteInterface() interface{} {
    return []byte("foo")
}

func main() {
    i := byteInterface()

    if b, ok := i.([]byte); ok {
      // use b as []byte
      println(len(b))
    } else {
      panic("should have bytes")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 非常简单.谢谢,我会在计时器启动时接受. (2认同)