Go by Example : Map

A map is a collection of key-value pairs in Go. It is used to store and retrieve values based on a key.

Here’s an example of how to declare and use a map in Go:

package main

import "fmt"

func main() {
    a := map[string]int{"foo": 42, "bar": 23}
    fmt.Println(a)

    b := make(map[string]int)
    b["foo"] = 42
    b["bar"] = 23
    fmt.Println(b)

    c := b["foo"]
    fmt.Println(c)

    d, ok := b["baz"]
    fmt.Println(d, ok)
}

Output:

map[bar:23 foo:42]
map[bar:23 foo:42]
42
0 false

You can use the make function to create a map with a specified length:

e := make(map[string]int)
fmt.Println(e)

Output:

map[]

You can use the delete function to remove a key-value pair from a map:

f := map[string]int{"foo": 42, "bar": 23}
delete(f, "foo")
fmt.Println(f)

Output:

map[bar:23]

Maps are a powerful and flexible data structure in Go, and are used extensively in many applications.

In Go, keys in a map can be of any type that is comparable, such as string, int, or float. Values in a map can be of any type.

It is important to note that the order of elements in a map is not guaranteed to be the same as the order in which they were added. If you need to maintain the order of elements, you can use a slice of structs or a linked list.

Here’s an example of using different types of keys and values in a map:

type person struct {
    name string
    age  int
}

func main() {
    a := map[string]person{
        "John": {name: "John", age: 30},
        "Jane": {name: "Jane", age: 25},
    }
    fmt.Println(a)

    b := map[int]string{
        1: "one",
        2: "two",
        3: "three",
    }
    fmt.Println(b)

    c := map[float64]bool{
        3.14: true,
        2.71: false,
    }
    fmt.Println(c)
}

Output:

map[Jane:{Jane 25} John:{John 30}]
map[1:one 2:two 3:three]
map[2.71:false 3.14:true]

Maps are a convenient and efficient way to store and retrieve values based on a key in Go. They are widely used in many applications and are a fundamental data structure in the language.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *