[Go] Use a struct as a map key

Created on November 28, 2026

You can use a struct as a key in a Go map. The example below defines a struct named key and uses it as the key type for the map m.

package main

import "fmt"

type key struct {
    a string
    b string
}

func main() {
    m := make(map[key]int)
    m[key{a: "one", b: "two"}] = 1
    fmt.Printf("%#v", m)
}

The program produces the following output.

map[main.key]int{main.key{a:"one", b:"two"}:1}

Structs with the same values for the same fields are treated as the same key even if the fields are listed in a different order in the literals. The second assignment below overwrites the first value.

package main

import "fmt"

type key struct {
    a string
    b string
}

func main() {
    m := make(map[key]int)
    m[key{a: "one", b: "two"}] = 1
    m[key{b: "two", a: "one"}] = 2
    fmt.Printf("%#v", m)
}

The program produces the following output.

map[main.key]int{main.key{a:"one", b:"two"}:2}
Go