Go Language Map

Foreword

HashTable is a clever and practical data structure is an unordered key/valuecollection of pairs, wherein all of the key is different by a given keycan be retrieved in constant time complexity, update or delete the corresponding value. Map is actually a Hashlist of references, you can quickly retrieve the data based on the key, the same key as the index value associated with the key point of. Have the opportunity to give you speak Mapthe bottom of things, it teaches you how to use Mapthe focus of this section is to remember one thing: Mapstore unordered collection of key-value pairs.

Creation and initialization

Make use function

makeYou can create a slice, it can also be used to create Map. Rule is this:

m := make(map[keyType]valueType)

Let's try to create:

month := make(map[string]int)
month["January"] = 1
month["February"] = 2
month["March"] = 3

The first line of code, create a keytype string, valuetype intof blank Map month, then to monthassign the three pairs.

Use literal

The above code, literal manner may be employed to achieve:

month := map[string]int{"January":1,"February":2,"March":3}
// 还可以写成这样
month := map[string]int{
    "January":1,
    "February":2,
    "March":3,
}

Use literals can also create empty Map, braces which are not assigned to it:

month := map[string]int{}
fmt.Println(month)        // 输出:map[]

Free Map, is not there nil Map? Promising course nilof Map:

var month map[string]int
fmt.Println(month == nil)    // 输出:true

For nilthe mapcan not access key-value pairs, otherwise it will error panic: assignment to entry in nil map. You can use mentioned makefunctions, to their initialization:

var month map[string]int
month = make(map[string]int)
month["January"] = 1
fmt.Println(month)   // 输出:map[January:1]

Nature can think of, Mapthe value is zero nil, Mapthat is, the underlying Hashreference tables.
MapThe keymay be a built-in type, structure type may be, may be used as long as the ==comparison operators, can be used as key. Sections, functions, and structures of the type comprising sections, because of these types reference semantics, not as keythe use of these types of errors will result in compilation:

month := map[[]string]int{}
// 编译错误:invalid map key type []string

For Mapin valueit, there would be no restrictions on the type of course there is no reason to prevent users from using the slice as Mapvalues:

m := map[string][]int{}
slice := []int{1,2,3}
m["slice"] = slice
fmt.Println(m["slice"])

// 或者
slice := []int{1,2,3}
m := map[string][]int{"slice":slice}
fmt.Println(m["slice"])

First piece of code, create a keytype string, a value of slicetype null Map, then slice sliceassigned to the called sliceof key. The second paragraph of the code is a shorthand version of the first paragraph of the code.

How to use the Map

MapThe use is very simple, similar to the array, the array is to use the index Mapto use keyto obtain or modify value.

m := map[string]int{}
m["January"] = 1        // 赋值
fmt.Println(m)            // 输出:map[January:1]
m["January"] = 10       //修改
fmt.Println(m)          // 输出:map[January:10]
january := m["January"]   // 获取value
fmt.Println(january)     // 输出:10

When modify operation, if keyalready exists, the new value will overwrite the old value, the above code has been manifested, so keyis not allowed to repeat.
Gets a nonexistent keyin valuetime, will return zero values corresponding to the type, this time, we do not know is there is a zero value or key-value pairs for it does not exist. Fortunately, Mapit provides us with a method:

february,exists := m["February"]
fmt.Println(february,exists)   // 输出:0 false

Get more value when a return value, the return value is the first value, the second is the return value booleantype variable indicating valuewhether or not there. This gives us a judgment keywhether there is provides a great convenience.

Delete key to delete

Unlike Slice, Goprovides us with a key to the delete function - deletefunction.
Prototype:

m := map[string]int{
    "January":1,
    "February":2,
    "March":3,
}
fmt.Println(m)     // 输出:map[March:3 January:1 February:2]
delete(m,"January")
fmt.Println(m)     // 输出:map[February:2 March:3]

When you delete a key-value pair does not exist, deletethe function does not complain, did not have any effect.

Traversal Map

MapCan not use forloop through, like an array, slice, can be used rangeto traverse.

for key, value := range m {
    fmt.Println(key, "=>", value)
}

Output:

February => 2
March => 3
January => 1

Blank operator can _ignore the return keyor value. When repeatedly executing code, you will find that the return value of the order is likely is not the same, that is to say Maptraversal is disordered.

len function

You can use len function returns the number of key-value pairs in the Map:

fmt.Println("len(m) =",len(m))

Map is a reference type

Map is a reference to the underlying data . The coding process, involves Mapcopying, transfer functions between Map and the like. With Slicesimilar Mapunderlying data points will not happen copyof.

m := map[string]int{
    "January":1,
    "February":2,
    "March":3,
}
month := m    
delete(month,"February")
fmt.Println(m)
fmt.Println(month)

Output:

map[January:1 March:3]
map[January:1 March:3]

The above code, Map mis assigned to month, delete montha key-value pair, malso changed, indicating that Mapcopying, mand monthshare the underlying data, wherein one of the data changes, the other will also change. Similarly, the transfer function between Mapwhen, in fact, passed a Mapreference to a copy of the underlying data will not be involved, if modified in the called function Map, in the calling function will be perceived Mapchanges.
What if I really want to copy Maphow to do?

month := map[string]int{}
m := map[string]int{
    "January":1,
    "February":2,
    "March":3,
}
for key,value := range m{
    month[key] = value
}
delete(month,"February")
fmt.Println(m)
fmt.Println(month)

Output:

map[January:1 February:2 March:3]
map[January:1 March:3]

The above code, we use rangethe mkey-value pairs assigned to the cycle month, and then remove monthone of the key-value pairs, it can be seen by the results of printing, mit has not changed. This enables a true copy.

Published 158 original articles · won praise 119 · views 810 000 +

Guess you like

Origin blog.csdn.net/u013474436/article/details/103991017