0% found this document useful (0 votes)
15 views2 pages

Go Maps: A Practical Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

Go Maps: A Practical Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Go by Example: Maps [Link]

com/maps

Go by Example: Maps
Maps are Go’s built-in associative data type
(sometimes called hashes or dicts in other
languages).

package main

import (
"fmt"
"maps"
)

func main() {

To create an empty map, use the builtin make: m := make(map[string]int)


make(map[key-type]val-type).

Set key/value pairs using typical name[key] = val m["k1"] = 7


syntax. m["k2"] = 13

Printing a map with e.g. [Link] will show all [Link]("map:", m)


of its key/value pairs.

Get a value for a key with name[key]. v1 := m["k1"]


[Link]("v1:", v1)

If the key doesn’t exist, the zero value of the value v3 := m["k3"]
type is returned. [Link]("v3:", v3)

The builtin len returns the number of key/value [Link]("len:", len(m))


pairs when called on a map.

The builtin delete removes key/value pairs from a delete(m, "k2")


map. [Link]("map:", m)

To remove all key/value pairs from a map, use the clear(m)


clear builtin. [Link]("map:", m)

The optional second return value when getting a _, prs := m["k2"]


value from a map indicates if the key was present [Link]("prs:", prs)
in the map. This can be used to disambiguate
between missing keys and keys with zero values
like 0 or "". Here we didn’t need the value itself,
so we ignored it with the blank identifier _.

You can also declare and initialize a new map in n := map[string]int{"foo": 1, "bar": 2}
the same line with this syntax. [Link]("map:", n)

The maps package contains a number of useful n2 := map[string]int{"foo": 1, "bar": 2}


utility functions for maps. if [Link](n, n2) {
[Link]("n == n2")
}
}

Note that maps appear in the form map[k:v k:v] $ go run [Link]
when printed with [Link]. map: map[k1:7 k2:13]
v1: 7
v3: 0
len: 2
map: map[k1:7]
map: map[]
prs: false
map: map[bar:2 foo:1]
n == n2

1 of 2 11/26/24, 23:27
Go by Example: Maps [Link]

Next example: Functions.

by Mark McGranaghan and Eli Bendersky | source | license

2 of 2 11/26/24, 23:27

You might also like