Check addressability and comparability
Check addressability and comparability
An addressable expression denotes a variable whose address can be taken. Variables and slice elements qualify; map elements do not. Comparability instead concerns whether == and != are permitted for a type. The two properties are independent.
package main
import ( "fmt")
func main() { s := []int{2} p := &s[0] *p = 5 m := map[string]int{"a": 5} fmt.Println(s[0], m["a"] == 5)}The slice element can be mutated through its address. The map lookup yields a comparable int but cannot be addressed. The map itself is not comparable except against nil. Taking the address of a composite literal is a specific permitted exception to the usual addressability requirement.
Expected output:
5 trueInspect a dynamic value before comparing
package main
import ( "fmt" "reflect")
func main() { var a any = []int{1} var b any = 3 fmt.Println(reflect.ValueOf(a).Comparable(), reflect.ValueOf(b).Comparable()) fmt.Println(b == 3)}Interface values are comparable by type, but comparing two interfaces with the same dynamically noncomparable type panics. Value.Comparable checks whether the represented value supports comparison without that panic. Use an explicit element-wise comparison for slices instead. Comparability does not imply ordering.
Expected output:
false truetrueTry it locally
Create a map of string to [2]int. Copy an entry into a local variable, mutate the local array using its address and store it back. Print the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 03: Check addressability and comparability
Check the lesson objective before moving on.
Can you take the address of a map entry?
Why can comparing two any values panic?