Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structs as keys in Go maps

I was looking into using structs as keys in golang maps. A field in this struct is supposed to be a map also and this seems to go against the documentation provided here which says that only structs that have fields that can be compared with == and != can be in the fields of structs that are used as keys in maps. I however went ahead to try the following:

package main  import "fmt" import "strings"  func main() {     fmt.Println("Hello, 世界")     fmt.Println(strings.Join([]string{"obi", "$", "56"}, ""))     z := make(map[string]float64)      z["obi"] = 0.003      x := &test{         name:"testing",         code:z,     }      a := &test{         name:"testing2",         code:z,     }      y := make(map[*test] string)      y[x] = "go home"     y[a] = "come home"      for key, val := range y{         fmt.Println(key.name, key.code, val)     }  }  type test struct{     name string     code map[string]float64 } 

The output was:

Hello, 世界 obi$56 testing map[obi:0.003] go home testing2 map[obi:0.003] come home 

This seems to go against the documentation as a field in the struct used as a key is a map. What do I seem to be getting wrong?

like image 885
cobie Avatar asked Jan 11 '14 15:01

cobie


People also ask

How do you use a struct as a key on a map?

By far the simplest is to define a global "less than" operator for your struct in stead of as a member function. std::map uses - by default - the 'lessthan' functor which, in turn, uses the global "operator<" defined for the key type of the map.

What can be a key in Golang map?

In the maps, a key must be unique and always in the type which is comparable using == operator or the type which support != operator. So, most of the built-in type can be used as a key like an int, float64, rune, string, comparable array and structure, pointer, etc.

How do you use structs in Golang?

A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming.

Are Golang map Keys ordered?

As a Golang map is an unordered collection, it does not preserve the order of keys.


2 Answers

In your example the map key is a pointer to the struct, not the struct itself. Pointers can be compared for equality even when the items they point to can't be compared. This comparison is not based on the contents of the item, but only on its memory address.

like image 78
andybalholm Avatar answered Sep 27 '22 21:09

andybalholm


only comparable type can be used as a key (== ,!=). struct (not a pointer) is comparable in case it contains only comparable types.

like image 38
15412s Avatar answered Sep 27 '22 21:09

15412s