Go Maps: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 29: Line 29:
=Operators=
=Operators=
==Indexing Operator <tt>[]</tt>==
==Indexing Operator <tt>[]</tt>==
Values stored in a map can be referenced with the indexing operator <code>[[Go_Language#Indexing_Operator|[]]]</code>, using the <code>[<key>]</code> syntax. The indexing operator returns two values: the value associated with the key, if any, and a boolean that says whether the key exists or not in the map.
<syntaxhighlight lang='go'>
mm := map[string]int{"A": 1, "B": 2}
v, ok := mm["A"]
fmt.Printf("%d, %t\n", v, ok) // will display 1, true
</syntaxhighlight>
If the key does not exist in map, the retuned value '''is not <code>nil</code>''', but the [[Go_Language#Zero_Value|zero value]] for the type.
The values can be changed, or new key/value pairs added with the same operator:
<syntaxhighlight lang='go'>
m["Alice"] = 7
println(m["Alice"])
m["Charlie"] = 9
println(m["Charlie"])
</syntaxhighlight>
=Map Functions=
=Map Functions=
==<tt>delete()</tt>==
==<tt>delete()</tt>==

Revision as of 23:38, 26 August 2024

External

Internal

Overview

Maps and Pass-by-Value

Pointers to Maps

nil and Empty Map

nil Map

Empty Map

Declaration and Initialization

Initialization with make()

Initialization with a Composite Literal

Composite literals can be used for map initialization.

Long variable declaration and initialization with type inference:

var mm = map[string]int{"A": 1, "B": 2}

Short variable declaration:

mm := map[string]int{"A": 1, "B": 2}

Operators

Indexing Operator []

Values stored in a map can be referenced with the indexing operator [], using the [<key>] syntax. The indexing operator returns two values: the value associated with the key, if any, and a boolean that says whether the key exists or not in the map.

mm := map[string]int{"A": 1, "B": 2}
v, ok := mm["A"]
fmt.Printf("%d, %t\n", v, ok) // will display 1, true

If the key does not exist in map, the retuned value is not nil, but the zero value for the type.

The values can be changed, or new key/value pairs added with the same operator:

m["Alice"] = 7
println(m["Alice"])

m["Charlie"] = 9
println(m["Charlie"])

Map Functions

delete()

len()

make()

new()

Iterating over a Map

TODO

Go_Maps_TODEPLETE