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.
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.
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}
Map elements can be accessed using the key inside square brackets.
value := m["a"]
fmt.Println(value)
Map elements can be modified by assigning a new value to a specific key.
m["a"] = 10
Map elements can be deleted using the delete
function.
delete(m, "b")
We can create and initialize a map in Go using the make function or a map literal.
For example,
m
using the make
function.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)
}
map[a:1 b:2] map[a:1 b:2]
We can access elements of a map in Go using the key inside square brackets.
For example,
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
value := m["a"]
fmt.Println(value)
}
1
We can modify elements of a map in Go by assigning a new value to a specific key.
For example,
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
m["a"] = 10
fmt.Println(m)
}
map[a:10 b:2]
We can delete elements from a map in Go using the delete function.
For example,
delete
function.package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
delete(m, "b")
fmt.Println(m)
}
map[a:1]