Golang interface{} to []byte Conversion: A Comprehensive Guide
To convert a Golang interface{} to []byte, you need to use type assertion to cast the interface to a byte array.
Example Code:
func InterfaceToBytes(i interface{}) ([]byte, error) {
switch v := i.(type) {
case []byte:
return v, nil
case string:
return []byte(v), nil
default:
return nil, fmt.Errorf('unsupported type: %T', i)
}
}
This function takes an interface{} type parameter i and checks if it's either a []byte or string type. If it is, it converts it to []byte and returns it; otherwise, it returns an error.
Usage Example:
b, err := InterfaceToBytes('hello world')
if err != nil {
log.Fatal(err)
}
fmt.Printf('%s
', b)
Output:
hello world
原文地址: https://www.cveoy.top/t/topic/lHbU 著作权归作者所有。请勿转载和采集!