I'm still new in golang. I want to know how I check if two arrays are considered equal if those arrays contain the same values in any order. I have read answers in this Comparing arrays in Go language and I know if I use ==
the arrays are considered equal if those arrays contain the same value in the same order.
for example, I want these arrays considered equal.
a := [3]int{1,2,3}
b := [3]int{3,2,1}
With Go 1.18 or later, you can use sort.Ints
to sort the arrays before comparison, and then slices.Equal
to compared the sorted slices. Something like:
func EqualIgnoringOrder(a, b []int) bool {
if len(a) != len(b) {
return false
}
sort.Ints(a)
sort.Ints(b)
return slices.Equal(a, b)
}
You would use it like this:
package main
import (
"fmt"
"sort"
"golang.org/x/exp/slices"
)
func EqualIgnoringOrder(a, b []int) bool {
if len(a) != len(b) {
return false
}
sort.Ints(a)
sort.Ints(b)
return slices.Equal(a, b)
}
func main() {
a := []int{1, 2, 3}
b := []int{3, 2, 1}
if EqualIgnoringOrder(a, b) {
fmt.Println("arrays are equal")
} else {
fmt.Println("arrays are not equal")
}
}
Notice that here I'm using slices rather than arrays; to quote https://go.dev/blog/slices , "Arrays are not often seen in Go programs because the size of an array is part of its type, which limits its expressive power."
We can't use ==
to compare slices, which is why we use slices.Equal
(which is only available for go 1.18 or later).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.