How to correctly compare two slices in Go for equality of elements and length?
Hello everyone! I recently started learning Go and encountered what seemed like a simple task. I need to compare two slices of integers to check if they contain the same elements in the same order (i.e., if they are "deeply equal").
In Python I would just write `if list1 == list2:` and it would work. But in Go I found that the `==` operator doesn't work for slices! The compiler gives an error: `slice can only be compared to nil`.
Here's an example of my code:
```go
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
if a == b { // Compilation error!
fmt.Println("Slices are equal")
}
}
```
I understand that a slice is a reference type (a descriptor with a pointer to the underlying array, length, and capacity). But how then do you correctly compare two slices?
No answers yet.
Log in to leave an answer
Blogs
Testing in Kotlin: Unit, Integration, E2E — Complete Guide