Go Maps
What are Maps?
Quite simply, maps map a key to a value. You can also think of maps as an unordered list of key-value pairs, with unique keys. Keys must have the same data type and values must have the same data types. However, keys and values don't need to have the same data type.
Creating a Map
Below is the general form of a map:
map1 := map[KeyType]ValueType{key1:value1, key2:value2,...}
Replace KeyType
with the data type of the keys and ValueType
with the data type of the values. Then, inside the curly brackets, you can put key:value
pairs, seperated by commas.
For example:
website := map[string]string{"name":"Learnmonkey", "founded":"2022", domain:"learnmonkey.github.io"}
Accessing Map Elements
To access a map element, we type map[key]
. For example:
website := map[string]string{"name":"Learnmonkey", "founded":"2022", domain:"learnmonkey.github.io"}
fmt.Println(website["name"])
fmt.Println(website["founded"])
fmt.Println(website["domain"])
The above code outputs:
Learnmonkey 2022 learnmonkey.github.io
Updating and Adding Map Elements
To add and update map elements, we simply type map[key] = value
.
Removing Map Elements
To remove map elements, we use the delete
function: delete(map, key)
Checking if a Map Element Exists
To check if a map element exists, we type:
x, y := map[key]
In the above code, x
represents the value of the value of the corresponding key (which will be empty if that key doesn't exist in the map) and y
is a boolean which is true if the key is in the map and is false if the key isn't in the map.
If we just want to check if a map element exists and not know the value, we can type:
_, y := map[key]
That way, the value won't be assigned to any variable.