如何获取此接口(interface)的 []byte 值?
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")
}
}
最佳答案
您可以使用 type assertion为了这;无需使用 reflect
包:
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")
}
}
关于reflection - 反射(reflect) []byte 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710022/