Back to: Golang
Go provides a built-in data structure called a map, which allows us to store key-value pairs. It is similar to dictionaries in Python, objects in JavaScript, and hash tables in other programming languages.
Go Map Syntax
In Go, a map is declared using the following syntax:
mapName := make(map[keyType]valueType)
Here, mapName
is the name of the map variable, keyType
is the data type of the key, and valueType
is the data type of the value.
For example, the following code creates a map named person
that stores the name and age of a person:
person := make(map[string]int)
person["John"] = 35
person["Sarah"] = 28
In addition to the make
function, we can also use a map literal to declare and initialize a map:
person := map[string]int{
"John": 35,
"Sarah": 28,
}
Accessing Map Values
We can access the values in the map using the keys:
fmt.Println(person["John"]) // Output: 35
Map Lenght
We can also use the len
function to get the number of key-value pairs in the map:
fmt.Println(len(person)) // Output: 2
Deleting Map Item
We can delete a key-value pair from the map using the delete
function:
delete(person, "John")
Go Map Example
Here is a code example on Go map with output:
package main
import "fmt"
func main() {
// Create an empty map with string keys and int values
students := make(map[string]int)
// Add values to the map
students["Alice"] = 85
students["Bob"] = 78
students["Charlie"] = 92
// Access values in the map
fmt.Println(students["Alice"])
// Update a value in the map
students["Bob"] = 80
// Delete a key-value pair from the map
delete(students, "Charlie")
// Iterate over the key-value pairs in the map
for name, grade := range students {
fmt.Println(name, "has a grade of", grade)
}
}
Output:
85
Alice has a grade of 85
Bob has a grade of 80
In this example, we create an empty map with string keys and int values using the make
function. We then add some key-value pairs to the map using the square bracket syntax. We access values in the map using the key in square brackets, update a value in the map using the same syntax, and delete a key-value pair using the delete
function.
We then use a for
loop and the range
keyword to iterate over the key-value pairs in the map, printing out each name and grade.
Note
Maps in Go are unordered, so we cannot rely on the order of the elements in the map.
Follow us on social media
Follow Author