Working with a Map in Go is like Dictionaries in Python, or Maps in Java. A Map stores information as key/value pairs. This is a nice thing about data structures, they are often found in other languages.
Defining the Map
When you define one in Go, you need to define the variable as a type called map, and then specify what the key and value will be. You don’t have to use a string and int, as is often seen in examples, it can be of any type that applies to your project, including your own user-defined data-type.
// general form
var data map[string]int
You can also use make if you want, or define it by giving it data.
// using make to define a map
myMap := make(map[string]int)
// defining a map by inference of the useage
myMap := map[string]int{
"apple": 1,
"banana": 2,
}
Adding and Updating Elements to the Map
To add elements to a map, you simply need to assign a value to a key that isn’t being used.
If you want to update an element, you will define a value to a key that is being used within the map.
// create elements in the map
myMap["apple"] = 1
myMap["banana"] = 2
// updating elements in the map
myMap["apple"] = 3
Removing Element From the Map
You can remove elements from a map using the delete()
function.
delete(myMap, "banana")
Checking to see if a Key Exists
You can use a multi-result value to see if a key exists.
value, exists := myMap["grape"]
if exists {
// Key exists
} else {
// Key does not exist
}
Iterating over the Map
You can loop over the values in a map using the for-each style of loop that Go provides.
for key, value := range myMap {
fmt.Println(key, value)
}
Working with Maps in Go was originally found on Access 2 Learn
One Comment
Comments are closed.