How use one byte buffer as key storage for map without copy?
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])
}
}
If BytesToString
is just string cast ( string(buffer) ), that method print:
a 1 b 1 c 1
but if BytesToString
has content:
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))
}
Result of function:
c 1 c 1 c 1
How use [a] ... byte [slice] ... as key ... for map?
You cannot. The language forbids slices as map keys as the content of a slice may change underhand (which is a property no map key must have).