Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a map[[16]byte][]string in Go?

Tags:

go

map

The Go spec states:

The comparison operators == and != (§Comparison operators) must be fully defined for operands of the key type; thus the key type must not be a struct, array or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.

I wish to create a map of hash values which come from the Hash interface, which returns []byte, but for which all my hashes are done with the same algorithm (thereby I know that it would fit into [16]byte). How can I provide the appropriate interface such that the map type will allow []byte or [16]byte or some wrapper thereof to be used as a key?

Presently my use generates the following error:

dupes := make(map[[16]byte][]string)
finddups.go:55: invalid map key type [16]uint8

Update (Mar 2012): Go1 allows [16]byte as key type.

like image 989
Matt Joiner Avatar asked Nov 26 '10 15:11

Matt Joiner


1 Answers

A string type represents the set of UTF-8 encoded string values. Strings behave like arrays of bytes. See rules 2 and 4 for byte slices in the Conversions to and from a string type topic in the Conversions section of The Go Language Specification.

package main

import "fmt"

func main() {
    dupes := make(map[string][]string)

    hash := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    dupes[string(hash)] = []string{"a", "b"}
    hash[len(hash)-1]++
    dupes[string(hash)] = []string{"b", "c"}

    fmt.Println("len:", len(dupes))
    for k, v := range dupes {
        fmt.Println("key:", []byte(k), "value:", v)
    }
}

Output:

len: 2
key: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16] value: [b c]
key: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] value: [a b]

Note: This algorithm merely takes advantage of the rules for string types and conversions given in The Go Language Specification, which all implementations must satisfy. It's a "trick", just like var i int = '7' - '0' (for ASCII, EBCDIC, Unicode, etc.) is a "trick" to convert a numeric character '7' to an integer value 7, in Go and many other languages.

like image 110
peterSO Avatar answered Sep 30 '22 22:09

peterSO