How do I retrieve the []byte value of this interface?
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")
}
}
Reflection is provided by the reflect package. It defines two important types, Type and Value . A Type represents a Go type. It is an interface with many methods for discriminating among types and inspecting their components, like the fields of a struct or the parameters of a function.
Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming.
The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With