1

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!")
}
}
1
  • 3
    "Are there any problems to use such a non UTF-8-encoded string for a map key regarding hashing?" have you tried trying it? If so, did you encounter any issues?
    – Adrian
    Jan 19, 2021 at 16:49

1 Answer 1

1

There is no problem using string as key in a map where the string is not valid UTF-8.

The Go Blog: Strings, bytes, runes and characters in Go:

In Go, a string is in effect a read-only slice of bytes.

And Spec: Comparison operators:

String values are comparable and ordered, lexically byte-wise.

What matters is what bytes the string has, may it be valid or non-valid UTF-8 sequence. If 2 string values have the same invalid UTF-8 byte sequence, they are equal, and if not, they aren't.

Testing invalid and valid sequences ("\xff" and "\x00"):

m := map[string]byte{}
m["\xff"] = 1
m["\x00"] = 2
fmt.Println(m["\xff"], m["\x00"])

Output is (try it on the Go Playground):

1 2
1
  • Thanks for your precise and fast answer :)
    – phil535
    Jan 19, 2021 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.