To check if two arrays are equal in Go, you can use a loop to compare each element for arrays with the same elements and use the reflect.DeepEqual
function for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.equal1
.equal1
is set to true
; otherwise, it's set to false
.equal1
to the console.package main
import (
"fmt"
)
func main() {
arr1 := []int{1, 2, 3}
arr2 := []int{1, 2, 3}
equal1 := true
for i := range arr1 {
if arr1[i] != arr2[i] {
equal1 = false
break
}
}
fmt.Println("Arrays are equal:", equal1)
}
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.reflect.DeepEqual
function to check if the arrays are equal and store the result in the variable equal2
.reflect.DeepEqual
function compares two interface{} values and returns true if they are deeply equal.equal2
to the console.package main
import (
"fmt"
"reflect"
)
func main() {
arr3 := []int{1, 2, 3}
arr4 := []int{3, 2, 1}
equal2 := reflect.DeepEqual(arr3, arr4)
fmt.Println("Arrays are equal:", equal2)
}
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in Go language with well detailed examples.