×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Language Comparing Arrays

Last Updated : April 20, 2025

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

Go: Comparing Arrays Exercise

Select the correct option to complete each statement about comparing arrays in Go.

  1. In Go, two arrays can be compared using the ___ operator.
  2. Arrays are equal if they have the same length and ___.
  3. If you try to compare arrays of different types, the code will ___.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.