How can I check if t...
How can I check if t...
To check if two slices are equal in Go, you have several methods available depending on the version of Go you are using and the specific requirements of your comparison. Here are the primary methods:
For Go version 1.21 and later, you can use the Equal
function from the slices
package in the standard library. This function compares two slices for equality, where equality means both slices have the same length and corresponding elements are equal.
package main
import (
"fmt"
"slices"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println("Slices equal:", slices.Equal(a, b))
}
For a more general solution that works with slices of any type, you can use reflect.DeepEqual
. This function from the reflect
package checks if two slices are deeply equal, meaning all corresponding elements and their sub-elements are equal.
package main
import (
"fmt"
"reflect"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println("Slices equal:", reflect.DeepEqual(a, b))
}
If you need a custom comparison logic or are using an older version of Go that does not support the slices
package, you can write your own function to compare two slices. This method involves iterating over the slices and comparing each element.
package main
import "fmt"
func slicesEqual(a, b []int) bool...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào