2 回答

TA贡献1712条经验 获得超3个赞
虽然使用 astring显然是更好的方法,但如果您不控制的代码使用字节数组作为键,那么您可以使用反射将字节切片转换为数组作为接口。
varr := reflect.New(reflect.ArrayOf(len(slice), reflect.TypeOf(uint8(0))))
reflect.Copy(varr.Elem(), reflect.ValueOf(slice))
return varr.Elem().Interface()
在使用它之前请考虑其他选项。
游乐场: https: //play.golang.org/p/CXsxZwgjiRR

TA贡献1821条经验 获得超4个赞
使用string而不是固定大小的字节数组。一个字符串可以保存任意的字节序列。
func getHashable(value interface{}) interface{} {
rfl := reflect.ValueOf(value)
if rfl.Kind() == reflect.Slice && rfl.Type().Elem().Kind() == reflect.Uint8 {
value = string(rfl.Bytes())
}
return value
}
如果您只需要处理[]byte而不是命名类型[]byte,请使用类型断言而不是反射:
func getHashable(value interface{}) interface{} {
switch value := value.(type) {
case []byte:
return string(value)
default:
return value
}
}
如果地图的用户需要区分字符串键和从 []byte 创建的键,请定义一个字符串类型来区分这些值:
type convertedSlice string
string()将上面代码中的转换使用替换为convertedSlice().
该应用程序可以通过以下方式检查转换后的密钥:
_, ok := key.(convertedSlice) // ok is true if key is converted slice.
并将密钥转换回 []byte :
cv, ok := key.(convertedSice)
if ok {
key = []byte(cv)
}
- 2 回答
- 0 关注
- 102 浏览
添加回答
举报