What do a == b and m[b] print for two equal point structs, and why?
Read the snippet below. Two point structs a and b are built from the same field values, and b is used to look up a map keyed by a.
Determine what a == b and m[b] print, and explain why — including what would change if point held a slice field.
type point struct{ x, y int }
func main() {
a := point{1, 2}
b := point{1, 2}
fmt.Println(a == b)
m := map[point]string{a: "p"}
fmt.Println(m[b])
}
Predict the output.
It prints true and p. Structs are comparable with == when every field is comparable (no slices/maps/funcs), comparing field by field. Because a == b, they hash to the same map key, so m[b] finds the value under a. If point held a slice field, both the == and the map-key use would fail to compile.
- ✗Thinking
==on structs compares identity rather than field-by-field values - ✗Believing a struct with a slice or map field is still comparable — it fails to compile
- ✗Forgetting that two equal structs hash to the same map key
- →Which field types make a struct non-comparable, and what is the compile error?
- →How can you still use a struct with a slice field as a map key?
What does this code print?
type point struct{ x, y int }
func main() {
a := point{1, 2}
b := point{1, 2}
fmt.Println(a == b) // ?
m := map[point]string{a: "p"}
fmt.Println(m[b]) // ?
}
Output
true
p
Why
A struct is comparable with == when every field is comparable. point has two int fields, so == compares them field by field by value: a.x == b.x && a.y == b.y → true. Variable identity or addresses play no role.
Comparability also makes the type usable as a map key. Because a == b, they hash to the same slot, so m[b] finds the value stored under a → p.
⚠️ Trap: adding a non-comparable field breaks both == and the map key — at compile time:
type point struct{ x, y int; tags []string } // a slice is non-comparable
// invalid operation: a == b (struct containing []string cannot be compared)
// invalid map key type point
Work around it by extracting the comparable part into a separate key, or by comparing with reflect.DeepEqual (which cannot serve as a map key).