0
0
GoHow-ToBeginner · 3 min read

How to Compare Arrays in Go: Syntax and Examples

In Go, you can compare arrays directly using the == operator if they have the same length and element type. This operator returns true if all elements are equal in order, otherwise false. For slices, you need to compare elements manually or use helper functions.
📐

Syntax

To compare two arrays in Go, use the == operator between them. Both arrays must have the same length and element type.

  • array1 == array2: returns true if all elements match in order.
  • Arrays of different lengths or types cannot be compared directly.
go
var a1 [3]int = [3]int{1, 2, 3}
var a2 [3]int = [3]int{1, 2, 3}

if a1 == a2 {
    // arrays are equal
}
💻

Example

This example shows how to compare two arrays using the == operator and print the result.

go
package main

import "fmt"

func main() {
    a1 := [3]int{1, 2, 3}
    a2 := [3]int{1, 2, 3}
    a3 := [3]int{3, 2, 1}

    fmt.Println("a1 == a2:", a1 == a2) // true
    fmt.Println("a1 == a3:", a1 == a3) // false
}
Output
a1 == a2: true a1 == a3: false
⚠️

Common Pitfalls

Arrays can be compared directly, but slices cannot because they are references. Trying to compare slices with == causes a compile error.

To compare slices, you must compare their lengths and elements manually or use a helper function like reflect.DeepEqual.

go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    s1 := []int{1, 2, 3}
    s2 := []int{1, 2, 3}

    // This line would cause a compile error:
    // fmt.Println(s1 == s2)

    // Correct way using reflect.DeepEqual:
    fmt.Println("s1 equals s2:", reflect.DeepEqual(s1, s2))
}
Output
s1 equals s2: true
📊

Quick Reference

ConceptDetails
Array comparisonUse == if arrays have same length and type
Slice comparisonCannot use ==, use manual loop or reflect.DeepEqual
Compile errorComparing slices with == causes error
Element orderArrays must have elements in same order to be equal

Key Takeaways

Use the == operator to compare arrays of the same length and type in Go.
Slices cannot be compared with ==; use reflect.DeepEqual or manual comparison instead.
Array comparison checks each element in order for equality.
Trying to compare slices with == causes a compile-time error.
For slices, always check length and elements to determine equality.