Maps (also called hashes or dicts in other languages) are one of Go’s built-in associative data types. A map maps keys to values. In that sense, a map stores key-value pairs.
The map data structure is used for fast lookups, retrieval, and deletion of data based on keys. It is one of the most widely-used data structures in computer science.
Map types are reference types like pointers or slices; so, the value of the above m is nil as it doesn’t point to an initialized map. Any attempt to write to a nil map will cause a runtime panic.
var m = make(map[KeyType]ValueType)
package mainimport "fmt"func main() {// declaring a mapvar mymap map[string]int// initializing the mapmymap = make(map[string]int)if mymap == nil {fmt.Println("mymap is nil")} else {fmt.Println("mymap is not nil")}}
Since each key can map to, at most, one value, a map cannot contain identical keys.
package mainimport "fmt"func main() {// declaring a mapvar mymap map[string]int// initializing the mapmymap = make(map[string]int)mymap["Pakistan"] = 92mymap["India"] = 91fmt.Println(mymap)}
package mainimport "fmt"func main() {// declaring a mapvar mymap map[string]int// initializing the mapmymap = make(map[string]int)mymap["Pakistan"] = 92mymap["India"] = 91// Accessing a specific value in the mapvar stored_value = mymap["Pakistan"]fmt.Println(stored_value)}
This can be further understood using the code:
package mainimport "fmt"func main() {// declaring a mapvar mymap map[string]int// initializing the mapmymap = make(map[string]int)mymap["Pakistan"] = 92mymap["India"] = 91fmt.Println("Before deletion, mymap:", mymap)delete(mymap, "Pakistan")fmt.Println("After deletion, mymap:", mymap)}
package mainimport "fmt"func main() {// declaring a mapvar mymap map[string]int// initializing the mapmymap = make(map[string]int)mymap["Pakistan"] = 92mymap["India"] = 91mymap["USA"] = 1for country, code := range mymap {fmt.Println(country, code)}}
A map is an unordered collection; therefore, the iteration order of a map is not guaranteed to be the same every time you iterate over it.
Free Resources