Как использовать один байтовый буфер в качестве хранилища ключей для карты без копирования?
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
- это просто приведение строки (строка (буфер)), этот метод print:
a 1 b 1 c 1
, но если 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))
}
Результат функции:
c 1c 1 c 1