Go 如何使用单字节缓冲区作为map的密钥存储?
如何使用单字节缓冲区作为map的密钥存储而不复制Go 如何使用单字节缓冲区作为map的密钥存储?,go,Go,如何使用单字节缓冲区作为map的密钥存储而不复制 func TestMap(t *testing.T) { testMap := make(map[string]int) //byteKey := make([]byte, 2) //byteKey[0] = 0 byteKey := make([]byte, 1) { byteKey[0] = 'a' key := BytesToString(byteKey)
func TestMap(t *testing.T) {
testMap := make(map[string]int)
//byteKey := make([]byte, 2)
//byteKey[0] = 0
byteKey := make([]byte, 1)
{
byteKey[0] = 'a'
key := BytesToString(byteKey)
testMap[key] += 1
}
{
byteKey[0] = 'b'
key := BytesToString(byteKey)
testMap[key] += 1
}
{
byteKey[0] = 'c'
key := BytesToString(byteKey)
testMap[key] += 1
}
for key, _ := range testMap {
println(key, testMap[key])
}
}
如果BytesToString
只是字符串转换(字符串(缓冲区)),则该方法将打印:
a 1
b 1
C1
但是如果BytesToString
包含内容:
func BytesToString(b []byte) string {
bytesHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
strHeader := reflect.StringHeader{Data: bytesHeader.Data, Len: bytesHeader.Len}
return *(*string)(unsafe.Pointer(&strHeader))
}
功能结果:
C1
C1
C1
如何使用[a]。。。字节[片]。。。作为关键。。。地图
你不能。该语言禁止将切片作为映射键,因为切片的内容可能会在暗中更改(这是任何映射键都不必具有的属性)。经验法则:切勿使用不安全的包。尤其是如果你不精通这门语言。语言明确禁止您尝试做的事情。不管你想做什么,都不要做。@Volker是对的,字符串在Go中是不可变的,使用
unsafe
规避这个限制是非常不受鼓励的。从代码的外观来看,您知道字符串只是一对指针和长度。由于您指向的是同一个内存位置,因此对所有内容都使用相同的键--byteKey
。这就是为什么,您将“c”-您上次的更新-视为所有人的密钥。那么基于地址的密钥散列呢?