Slices in Go usually are not comparable, so a easy equality comparability a == b
will not be doable. To examine if two slices are equal, write a customized operate that compares their lengths and corresponding parts in a loop.
Word that evaluating two arrays is doable:
a := [2]string{"strawberry", "raspberry"} b := [2]string{"strawberry", "raspberry"} fmt.Printf("slices equal: %tn", a == b)
bundle fundamental
import "fmt"
func stringSlicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := vary a {
if v != b[i] {
return false
}
}
return true
}
func fundamental() {
a := []string{"strawberry", "raspberry"}
b := []string{"strawberry", "raspberry"}
fmt.Printf("slices equal: %tn", stringSlicesEqual(a, b))
b = append(b, "check")
fmt.Printf("slices equal: %tn", stringSlicesEqual(a, b))
}
Output:
slices equal: true
slices equal: false
You can too use the mirror.DeepEqual()
operate that compares two values recursively, which suggests it traverses and checks the equality of the corresponding information values at every degree. Nonetheless, this answer is far slower and fewer protected than evaluating values in a loop. A normal rule of thumb when utilizing the mirror
bundle is: it needs to be used with care and averted until strictly obligatory.
bundle fundamental
import (
"fmt"
"mirror"
)
func fundamental() {
a := []string{"strawberry", "raspberry"}
b := []string{"strawberry", "raspberry"}
fmt.Printf("slices equal: %tn", mirror.DeepEqual(a, b))
b = append(b, "check")
fmt.Printf("slices equal: %tn", mirror.DeepEqual(a, b))
}
Output:
slices equal: true
slices equal: false