patterngoCritical
Checking the equality of two slices
Viewed 0 times
slicesthecheckingtwoequality
Problem
How can I check if two slices are equal, given that the operators
This does not compile with:
invalid operation: s1 == s2 (slice can only be compared to nil)
== and != are not an option?package main
import "fmt"
func main() {
s1 := []int{1, 2}
s2 := []int{1, 2}
fmt.Println(s1 == s2)
}This does not compile with:
invalid operation: s1 == s2 (slice can only be compared to nil)
Solution
You need to loop over each of the elements in the slice and test. Equality for slices is not defined. However, there is a
bytes.Equal function if you are comparing values of type []byte.func testEq(a, b []Type) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}Code Snippets
func testEq(a, b []Type) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}Context
Stack Overflow Q#15311969, score: 230
Revisions (0)
No revisions yet.