A Quiz of Equal Operator in Go

When was the last time you took a quiz? Photo by Jason Sung on Unsplash

Quiz

// 1
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println(a == b)
// 2
a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
fmt.Println(a == b)
// 3
a := [4]int{1, 2, 3}
b := [4]int{1, 2, 3}
fmt.Println(a == b)
// 4
a := map[string]bool{"go": true}
b := map[string]bool{"go": true}
fmt.Println(a == b)
// 5
a := func(n int) bool { return n%2 == 0 }
b := func(n int) bool { return n%2 == 0 }
fmt.Println(a == b)
// 6
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println(&a == &b)

Answers

1
Failed to build
invalid operation: a == b (slice can only be compared to nil)
2
true
3
true
4
Failed to build
invalid operation: a == b (map can only be compared to nil)
5
Failed to build
invalid operation: a == b (func can only be compared to nil)
6
false

Explanation

Slice literal and array literal

Slice, map and function value can only compare to nil

a := []int{1, 2, 3}
b := []int{1, 2, 3}
ai := interface{}(a)
bi := interface{}(b)
fmt.Println(ai == bi)
$ go run main.go
panic: runtime error: comparing uncomparable type []int

Pointer values are comparable

Conclusion

Reference

Senior Software Engineer@Instana, Programming / Human Language Enthusiast. Located in Munich, Germany

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store