Go Maps


Go Maps

A map, called a dictionary in other languages, “maps” keys to values.
A map is declared like this:

var m map[Key]Value

This map has no keys and no keys can be added to it.
To create a map, use the make function:

m = make(map[Key]Value)

Anything can be used as a key or as a value.

Modifying maps

Here are some common action with maps.

Inserting/Changing elements

Create or change element foo in map m:

m["foo"] = bar

Getting elements

Get element with key foo in map m:

element = m["foo"]

Deleting elements

Delete element with key foo in map m:

delete(m, "foo")

Check if a key has been used

Check if key foo has been used in map m:

element, ok = m["foo"]

If ok is true, the key has been used and element holds the value at m["foo"].
If ok is false, the key has not been used and element holds its zero-values.

Map literals

You can directly create map literals:

var m = map[string]bool{ "Go": true, "JavaScript":false, } m["Go"] // true m["JavaScript"] = true // Set JavaScript to true delete(m, "JavaScript") // Delete "JavaScript" key and value language, ok = m["C++"] // ok is false, language is bool's zero-value (false)

More Information:

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.