Comparing two maps in Go

Follow the latest of Whizdumb’s journey here.

I have started learning Go these days, and have revived this blog and will be using it to share what all I learn in Go.

Lets start with looking at how we can compare two maps

package main

import "fmt"
import "reflect"
func main() {
var x map[int]int
var y map[int]int
x = make(map[int]int)
y = make(map[int]int)
x[1] = 10
y[1]=10
eq := reflect.DeepEqual(x, y)
if eq {
fmt.Println ("The two maps are equal")
}else{
fmt.Println ("The two maps are not equal")
}
}

In the above code to compare map, we have imported the reflect package, which provides a DeepEqual() method.

We have used reflect.DeepEqual(x,y) where x and y are two maps to be compared and we receive a boolean value as result. We have stored that boolean value in a new variable called eq.

In the above example two maps are equal. You can run the above code here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s