create a map with a key of type struct in go

To create a map with a key of type struct in Go, you first need to define your struct. For example:

main.go
type Person struct {
    FirstName string
    LastName  string
}
65 chars
5 lines

Then, you can create a map with keys of type Person:

main.go
people := make(map[Person]int)
31 chars
2 lines

You can then add items to the map as follows:

main.go
person1 := Person{FirstName: "John", LastName: "Doe"}
people[person1] = 42

person2 := Person{FirstName: "Jane", LastName: "Doe"}
people[person2] = 99
151 chars
6 lines

You can access values in the map using a key of type Person as follows:

main.go
fmt.Println(people[person1]) // Output: 42
43 chars
2 lines

And you can iterate over the map using a for ... range loop:

main.go
for person, value := range people {
    fmt.Printf("%v scored %d\n", person, value)
}
// Output:
// {John Doe} scored 42
// {Jane Doe} scored 99
145 chars
7 lines

gistlibby LogSnag