Maps in Go
In this tutorial, we will learn about maps in Go. We will cover the basics of defining and using maps, including how to create, access, modify, and delete map elements.
Understanding Maps in Go
A map in Go is an unordered collection of key-value pairs. Maps are used to store data in the form of key-value pairs, where each key is unique.
Creating a Map
Maps in Go can be created using the make
function or by defining a map literal.
var m map[string]int
m = make(map[string]int)
// or using map literal
m := map[string]int{"a": 1, "b": 2}
Accessing Map Elements
Map elements can be accessed using the key inside square brackets.
value := m["a"]
fmt.Println(value)
Modifying Map Elements
Map elements can be modified by assigning a new value to a specific key.
m["a"] = 10
Deleting Map Elements
Map elements can be deleted using the delete
function.
delete(m, "b")
Example 1: Creating and Initializing a Map
We can create and initialize a map in Go using the make function or a map literal.
For example,
- Create a map variable named
m
using themake
function. - Initialize a map variable using a map literal with key-value pairs.
- Print the map to the console.
Go Program
package main
import "fmt"
func main() {
var m map[string]int
m = make(map[string]int)
m["a"] = 1
m["b"] = 2
fmt.Println(m)
// or using map literal
n := map[string]int{"a": 1, "b": 2}
fmt.Println(n)
}
Output
map[a:1 b:2] map[a:1 b:2]
Example 2: Accessing Map Elements
We can access elements of a map in Go using the key inside square brackets.
For example,
- Create and initialize a map.
- Access an element by its key and assign it to a variable.
- Print the value to the console.
Go Program
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
value := m["a"]
fmt.Println(value)
}
Output
1
Example 3: Modifying Map Elements
We can modify elements of a map in Go by assigning a new value to a specific key.
For example,
- Create and initialize a map.
- Modify the value of an existing key.
- Print the modified map to the console.
Go Program
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
m["a"] = 10
fmt.Println(m)
}
Output
map[a:10 b:2]
Example 4: Deleting Map Elements
We can delete elements from a map in Go using the delete function.
For example,
- Create and initialize a map.
- Delete an element by its key using the
delete
function. - Print the modified map to the console.
Go Program
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
delete(m, "b")
fmt.Println(m)
}
Output
map[a:1]