Home »
Golang
Go Language - Comparing Arrays
In Go, arrays can be compared using the equality operator (==
). This comparison checks if both arrays have the same length and elements in the same order.
Comparing Arrays Using == Operator
Go allows direct comparison of arrays using the ==
operator. Below is an example:
Example
package main
import "fmt"
func main() {
arr1 := [3]int{1, 2, 3}
arr2 := [3]int{1, 2, 3}
arr3 := [3]int{4, 5, 6}
fmt.Println("arr1 == arr2:", arr1 == arr2) // true
fmt.Println("arr1 == arr3:", arr1 == arr3) // false
}
When executed, this program outputs:
arr1 == arr2: true
arr1 == arr3: false
Comparing Arrays Element by Element
If the array size is unknown or the arrays have different lengths, the ==
operator cannot be used directly. Instead, elements must be compared individually:
Example
package main
import "fmt"
func compareArrays(arr1, arr2 []int) bool {
if len(arr1) != len(arr2) {
return false
}
for i := range arr1 {
if arr1[i] != arr2[i] {
return false
}
}
return true
}
func main() {
arr1 := []int{1, 2, 3}
arr2 := []int{1, 2, 3}
arr3 := []int{4, 5, 6}
fmt.Println("arr1 == arr2:", compareArrays(arr1, arr2)) // true
fmt.Println("arr1 == arr3:", compareArrays(arr1, arr3)) // false
}
When executed, this program outputs:
arr1 == arr2: true
arr1 == arr3: false
Advertisement
Advertisement