Go Tutorials

Go Programs

Go Maps


Go Maps

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")


Creating and Initializing a Map

We can create and initialize a map in Go using the make function or a map literal.

For example,

  1. Create a map variable named m using the make function.
  2. Initialize a map variable using a map literal with key-value pairs.
  3. 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]


Accessing Map Elements

We can access elements of a map in Go using the key inside square brackets.

For example,

  1. Create and initialize a map.
  2. Access an element by its key and assign it to a variable.
  3. 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


Modifying Map Elements

We can modify elements of a map in Go by assigning a new value to a specific key.

For example,

  1. Create and initialize a map.
  2. Modify the value of an existing key.
  3. 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]


Deleting Map Elements

We can delete elements from a map in Go using the delete function.

For example,

  1. Create and initialize a map.
  2. Delete an element by its key using the delete function.
  3. 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]