Provide Best Programming Tutorials

How to use map in Golang

the map is a very important and popular data structure in all programming languages.

In Golang you can easily define and use the map, generally speaking, you have 3 ways to use it, let me show you how:

Way 1

	var a map[string]string
	a = make(map[string]string, 10)

	a["no1"] = "Java"
	a["no2"] = "GO"
	a["no1"] = "Python"
	a["no3"] = "Python"
	fmt.Println(a)

Notice you need to invoke the embedded method make to create the space for the map first otherwise you will get compile error.

in way 1 we define the map and at the same time we say that this map’s capacity is 10 which means it can hold 10 string objects in it.

Way 2

cities := make(map[string]string)
cities["no1"] = "Beijing"
cities["no2"] = "Shanghai"
cities["no3"] = "LA"
fmt.Println(cities)

The only difference between way 2 and way 1 is that we don’t define the capacity for the cities map but left Golang itself to decide how much capacity it should have.

Way 3

counties := map[string]string{
		"name1": "China",
		"name2": "India",
		"name3": "USA",
	}
	fmt.Println(counties)

In this way, we define and initialize the map at the same time.

Leave a Reply

Close Menu