Welcome aboard for our journey with Go's maps. Maps, a built-in data type, make it easy to organize and find data within collections — a crucial feature for effective programming.
In Go, maps link one value (the key) to another value. Just imagine having a roster of students alongside their grades. With maps, you can quickly associate each student (the key) with their corresponding grade (the value).
Our quest today involves the following:
- Understanding how to craft and initiate Go's
maps. - Learning to interact with map elements.
- Fathoming the external behavior of maps as reference types in Go.
Let's dive in!
Declaring a map in Go is as easy as pie. For this purpose, you can utilize either the make function or a composite literal. Let's sketch an illustration:
As displayed above, we create maps that accommodate strings as keys and integers as their associated values.
Go's maps enable swift and effortless handling of map elements. Adding, changing, accessing values, or handling absent keys in a map is a cinch:
Notice how we use the key to access, update or delete an element. It is much more handy then indicies in the array. We can access "John"'s grade using his own name as an identifier!
Since maps are reference types in Go, assigning a map to a new map variable creates a reference, not a replica:
The output of both maps reflects the value 100 related to "apple". Here, copiedData is simply a reference to originalData, hence modifications enacted on copiedData affect originalData.
