I would like to use a bytearray of variable length as key within a map.
myMap := make(map[[]byte]int)
As slices and variable length bytearrays are no valid key type in go, the code above is not valid.
Then I read that strings are just a set of 8-bit bytes, conventinally but not necessarily representing UTF-8-encoded text.
Are there any problems to use such a non UTF-8-encoded string for a map key regarding hashing?
The following code demonstrates how I converted []byte to string and back to []byte again:
package main
import (
"bytes"
"fmt"
)
func main() {
// src is a byte array with all available byte values
src := make([]byte, 256)
for i := 0; i < len(src); i++ {
src[i] = byte(i)
}
fmt.Println("src:", src)
// convert byte array to string for key usage within a map
mapKey := string(src[:]) // <- can this be used for key in map[string]int?
//fmt.Println(mapKey) // <- this destroys the print function!
fmt.Printf("len(mapKey): %d\n", len(mapKey)) // <- that actually works
// convert string back to dst for binary usage
dst := []byte(mapKey)
fmt.Println("dst:", dst)
if bytes.Compare(src, dst) != 0 {
panic("Ups... something went wrong!")
}
}