Slices in Go are not comparable, so a simple equality comparison a == b
is not possible. To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop.
Note that comparing two arrays is possible:
a := [2]string{"strawberry", "raspberry"} b := [2]string{"strawberry", "raspberry"} fmt.Printf("slices equal: %t\n", a == b)
package main
import "fmt"
func stringSlicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
func main() {
a := []string{"strawberry", "raspberry"}
b := []string{"strawberry", "raspberry"}
fmt.Printf("slices equal: %t\n", stringSlicesEqual(a, b))
b = append(b, "test")
fmt.Printf("slices equal: %t\n", stringSlicesEqual(a, b))
}
Output:
slices equal: true
slices equal: false
You can also use the reflect.DeepEqual()
function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level. However, this solution is much slower and less safe than comparing values in a loop. A general rule of thumb when using the reflect
package is: it should be used with care and avoided unless strictly necessary.
package main
import (
"fmt"
"reflect"
)
func main() {
a := []string{"strawberry", "raspberry"}
b := []string{"strawberry", "raspberry"}
fmt.Printf("slices equal: %t\n", reflect.DeepEqual(a, b))
b = append(b, "test")
fmt.Printf("slices equal: %t\n", reflect.DeepEqual(a, b))
}
Output:
slices equal: true
slices equal: false