go / intermediate
Snippet
Using Structs as Comparable Map Keys
In Go, maps can use struct types as keys as long as all fields in the struct are comparable. Basic types like integers, strings, and booleans are comparable, allowing structs of these types to be used for multi-key dictionary lookups.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport "fmt"type Point struct {X, Y int}func main() {grid := make(map[Point]string)grid[Point{X: 1, Y: 2}] = "Starting Point"grid[Point{X: 3, Y: 4}] = "Destination"search := Point{X: 1, Y: 2}val, exists := grid[search]fmt.Printf("Found: %v, Exists: %v\n", val, exists)}
Breakdown
1
type Point struct {
Defines a Point struct with two comparable integer fields.
2
grid := make(map[Point]string)
Creates a map where the key is a Point struct and the value is a string.
3
grid[Point{X: 1, Y: 2}] = "Starting Point"
Inserts an entry using a struct literal directly as a map key.
4
val, exists := grid[search]
Looks up the value using a matching struct instance.