x
 
1
// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array)
2
// (sometimes called _hashes_ or _dicts_ in other languages).
3
4
package main
5
6
import "fmt"
7
8
func main() {
9
10
    // To create an empty map, use the builtin `make`:
11
    // `make(map[key-type]val-type)`.
12
    m := make(map[string]int)
13
14
    // Set key/value pairs using typical `name[key] = val`
15
    // syntax.
16
    m["k1"] = 7
17
    m["k2"] = 13
18
19
    // Printing a map with e.g. `Println` will show all of
20
    // its key/value pairs.
21
    fmt.Println("map:", m)
22
23
    // Get a value for a key with `name[key]`.
24
    v1 := m["k1"]
25
    fmt.Println("v1: ", v1)
26
27
    // The builtin `len` returns the number of key/value
28
    // pairs when called on a map.
29
    fmt.Println("len:", len(m))
30
31
    // The builtin `delete` removes key/value pairs from
32
    // a map.
33
    delete(m, "k2")
34
    fmt.Println("map:", m)
35
36
    // The optional second return value when getting a
37
    // value from a map indicates if the key was present
38
    // in the map. This can be used to disambiguate
39
    // between missing keys and keys with zero values
40
    // like `0` or `""`. Here we didn't need the value
41
    // itself, so we ignored it with the _blank identifier_
42
    // `_`.
43
    _, prs := m["k2"]
44
    fmt.Println("prs:", prs)
45
46
    // You can also declare and initialize a new map in
47
    // the same line with this syntax.
48
    n := map[string]int{"foo": 1, "bar": 2}
49
    fmt.Println("map:", n)
50
}
51
分享