golang interface{} 转 []byte
要将golang中的interface{}转换为[]byte,需要使用类型断言将接口转换为字节数组。
示例代码:
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)
}
}
该函数接收一个interface{}类型参数i,检查它是否是[]byte或string类型。如果是,则将其转换为[]byte并返回;否则返回一个错误。
使用示例:
b, err := InterfaceToBytes("hello world")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", b)
输出:
hello world
原文地址: https://www.cveoy.top/t/topic/uLM 著作权归作者所有。请勿转载和采集!