Maps
Sample code link: (https://repl.it/@jjoco/go-maps)
Go implements map, a key-value data structure similar to Dictionaries in Python and Hashtables/HashMaps in Java.
Creating a Map
A dev can use literal-based syntax or the make function to allocate memory for a new map.
1 2 3 4 5 6 7 |
|
- KeyType must be a type that is comparable => "boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types"
- ValueType can be of any type, including custom structs or other maps
- use
interface{}
as your ValueType to have the map's valueType be of anything
- use
Reading and Writing Map Elements
Like other languages, one can directly read, write, and delete values from Go maps.
1 2 3 4 5 6 7 |
|
Reading Map Element
1 2 |
|
1 2 |
|
Map Literals
Use map literals to define the initial elements in a map.
1 2 3 4 5 |
|
Iterating Through Maps
Similar in syntax to slice iteration, a dev can use range to iterate through the key-value pairs in a map.
1 2 3 |
|
- Can use
_
in place of key or value if they aren't needed
Example:
1 2 3 4 5 6 7 8 9 |
|
Getting a Key's Value if the pair exists
There is an optional second return value when reading from a map that tells the dev if a key-value pair exists.
Syntax
1 2 3 4 5 |
|
Checking for key-value existence
If you don't care for retrieving the value, one can just check the existence of the key-value pair.
1 2 3 4 5 |
|
1 2 3 4 5 6 7 |
|