如何检索此接口的[]字节值?
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")
}
}
答案 0 :(得分:7)
您可以使用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")
}
}