Go study notes the Map

Go study notes the Map

Map reference type, hash tables. The key map may be compared for equality, except slice, map, function as built-in types are key. struct type does not contain the above-described field can also be used as key.

map of operation

1. Create a map.

1 m := map[int]struct{
2     name string
3     age int     
4 }{
5     1: {"user1", 10},
6     2: {"user2", 20},
7 }
8 fmt.Println(m)

2. Use make to create. This map is empty.

m := make(map[string]int)  //map[key]value,m == empty

3. or define a map, this map is nil.

in the Var m into map Your page will, [ string is the ], int, that // m into == nil at half

2. Get element

1. Using the value, ok: = map [key] to determine whether there is key.

2. Use the delete delete elements.

m: = Map [ String ] int {
     " A " : . 1 ,   
} 

IF V, OK: m = [ " A " ]; OK {   // determines whether the key exists 
    the println (V) 
} the else { 
    the println ( " Not exist " ) 
} 

the println (m [ " C " ])    // for the absence of key, directly back \ 0, no error 

m [ " B " ] = 2   // add or edit 

Delete (m, " C " )    // delete, if the key does not exist, does not complain 

println (len (m))   // get the number of key-value pairs, cap invalid

 

map traversal

We can not guarantee the order of iteration returned.

m := map[string]string {
    "name": "ccmouse",
    "course": "golang",
    "site": "imooc",
}
fmt.Println("Traversing map")
for k,v := range m {
    fmt.Println(k, v)
}

输出:
course golang
site imooc
name ccmouse

 

Guess you like

Origin www.cnblogs.com/tulipgirl/p/11829410.html