Golang program to compare two arrays using equal to (==) operator

Here, we are going to learn how to compare two arrays using equal to (==) operator in Golang (Go Language)?
Submitted by Nidhi, on March 07, 2021 [Last updated : March 03, 2023]

Comparing two arrays in Golang

Problem Solution:

In this program, we will compare arrays using the equal to (==) operator and print the appropriate message on the console screen.

Program/Source Code:

The source code to compare two arrays using the equal to (==) operator is given below. The given program is compiled and executed successfully.

Golang code to compare two arrays using equal to (==) operator

// Golang program to compare two arrays
// using the equal to (==) operator.

package main

import "fmt"

func main() {
	arr1 := [...]int{1, 2, 3}
	arr2 := [...]int{1, 2, 3}
	arr3 := [...]int{4, 2, 3}

	if arr1 == arr2 {
		fmt.Println("Arr1 and Arr2 have the similar elements")
	} else {
		fmt.Println("Arr1 and Arr2 have not the similar elements")
	}

	if arr1 == arr3 {
		fmt.Println("Arr1 and Arr3 have the similar elements")
	} else {
		fmt.Println("Arr1 and Arr3 have not the similar elements")
	}

	if arr2 == arr3 {
		fmt.Println("Arr2 and Arr3 have the similar elements")
	} else {
		fmt.Println("Arr2 and Arr3 have not the similar elements")
	}
}

Output:

Arr1 and Arr2 have the similar elements
Arr1 and Arr3 have not the similar elements
Arr2 and Arr3 have not the similar elements

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created and initialized three integer arrays. After that perform the comparison between arrays using the equal to (==) operator and print an appropriate message on the console screen.

Golang Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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