Using a two-dimensional map of golang

Disclaimer: This article is a blogger original article, reprinted need to add a description link. https://blog.csdn.net/makenothing/article/details/89786679

Map

1.1 map

Map is a data type in golang, keys and values to be bound together. Can be obtained by corresponding to the key value, map using a hash to achieve, you can quickly find the corresponding key values. Type represents: map[keyType][valueType]for example: age' := make(map[string]int)using the built-in make function to initialize the map, and can only be used to make initialize map, because as a map nil, and add elements, without any meaning, it will result in a runtime error.

package main

import (  
    "fmt"
)
func main() {  
    var agemap[string]int
    if age== nil {
        fmt.Println("map is nil.")
        age= make(map[string]int)
    }
}

1.2 Map emptying

golang the map does not provide a clear map of built-in functions to empty, empty map, direct initialization on it:
For a certain collection of age data, clear way is initialized again: age = make(map[string]int)if the latter no longer use the map, you can directly: age= nilto achieve the purpose of clearing the data, but if you need to reuse, you must make initialized, or can not add anything to the map nil.

1.3 Map reference Properties

Like the slice, map is a reference type. When a map is assigned to a new variable, they all point to the same internal data structure. Therefore, a change which is also reflected in another

package main

import (
    "fmt"

)

func main() {
	age := map[string]int{
        "steve": 20,
        "jamie": 80,
    }
    fmt.Println("Ori age", age)
    newage:= age
    newage["steve"] = 18
    fmt.Println("age changed", age)
}
Ori age map[steve:20 jamie:80]
age changed map[steve:18 jamie:80]

2.1-D map

2.1.1 The two-dimensional map initialization

Two steps are required to initialize

yourMap := make(map[string]map[string]int)
for i, _ := range yourMap {
	yourMap[i] = make(map[string]int)
}

2.1.2 two-dimensional map of Clear

二维以及多维map的清空同一维map的原理是相同的,不再赘述。

Guess you like

Origin blog.csdn.net/makenothing/article/details/89786679