Comparable Structs As Map Keys

Use comparable structs and fixed-size arrays as map keys so composite coordinates collapse to one entry, while slice keys are a compile-time error.

GoData Integrity

Code

gosnippet
34 lines
package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	// 可比较类型都能做 map 键:结构体按字段值判等
	grid := map[Point]string{
		{0, 0}: "origin",
		{1, 2}: "depot",
	}

	// 值相等即命中同一条目,不会出现"重复键"
	grid[Point{1, 2}] = "warehouse"
	grid[Point{3, 1}] = "silo"
	fmt.Println("entries:", len(grid), "at (1,2):", grid[Point{1, 2}])

	// 缺失键给零值空串;comma-ok 区分未设置
	name, ok := grid[Point{9, 9}]
	fmt.Println("missing:", name, ok)

	// 定长数组键同理:坐标对更轻量
	byCell := map[[2]int][]string{}
	cell := [2]int{0, 0}
	byCell[cell] = append(byCell[cell], "seed", "water")
	fmt.Println("cell (0,0):", byCell[cell], "cells:", len(byCell))

	// 切片、map、函数不可比较,做键会编译报错:
	// invalid map key type
	fmt.Println("total entries:", len(grid)+len(byCell))
}

Under the hood

Comparable Structs As Map Keys reduces to the function main.

Applying it

Running the file prints labeled results such as entries:, missing:, cell (0,0): — each operation’s effect is visible in the output.

Statements that matter

byCell[cell] = append(byCell[cell], "seed", "water")

Interactive Tools for This Topic

FAQ

What does Comparable Structs As Map Keys print when run?
No setup needed: run the file and look for labeled lines like `entries:`, `missing:`, `cell (0,0):` in the output.