3

How to create a key as array in Go for map. For example in ruby I can implement it such:

quarters = {
  [1, 2, 3] => 'First quarter',
  [4, 5, 6] => 'Second quarter',
  [7, 8 ,9] => 'Third quarter',
  [10, 11, 12] => 'Fourh quarter',
}
quarters[[1, 2, 3]] 
# => "First quarter"

How the same will be looked in Golang ?

icza
  • 389,944
  • 63
  • 907
  • 827
itsnikolay
  • 17,415
  • 4
  • 65
  • 64

2 Answers2

8

Array types (unlike slices) in Go are comparable, so there is nothing magical in it: you can just define it like any other maps: map[KeyType]ValueType where KeyType will be [3]int and ValueType will be string.

The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.

m := map[[3]int]string{}

m[[3]int{1, 2, 3}] = "First quarter"
m[[3]int{4, 5, 6}] = "Second quarter"
m[[3]int{7, 8, 9}] = "Third quarter"
m[[3]int{10, 11, 12}] = "Fourth quarter"

fmt.Println(m)

Output:

map[[1 2 3]:First quarter [4 5 6]:Second quarter 
    [7 8 9]:Third quarter [10 11 12]:Fourth quarter]

Try it on the Go Playground.

To query an element:

fmt.Println(m[[3]int{1, 2, 3}]) // Prints "First quarter"

You can also create the map in one step:

m := map[[3]int]string{
    [3]int{1, 2, 3}:    "First quarter",
    [3]int{4, 5, 6}:    "Second quarter",
    [3]int{7, 8, 9}:    "Third quarter",
    [3]int{10, 11, 12}: "Fourth quarter",
}
icza
  • 389,944
  • 63
  • 907
  • 827
1

It should be noted that array in ruby and array in go are different data structures. Go array is not mutable, while ruby array is. Go slice is a lot more similar data structure to ruby array. However, you cannot use slices as keys in go, as pointed out in icza's answer.

So to answer your question:

How the same will be looked in Golang ?

It is impossible, you cannot have a dictionary that maps dynamic arrays to strings in go. However, you could convert slices to arrays and use them as keys, as very well explained by icza.

Akavall
  • 82,592
  • 51
  • 207
  • 251