The use of golang two-dimensional map

Map is a data type in golang that binds keys and values together. The corresponding value can be obtained through the key. The map is implemented by hash, and the corresponding value can be quickly found through the key. Type representation: map[keyType][valueType] For example: age’ := make(map[string]int) Use the built-in make function to initialize the map, and only use make to initialize the map, because for a nil map, add element, which has no meaning and will cause 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)
    }
}

Golang’s map does not provide a built-in function for clearing the map. Clear the map and initialize it directly: For a collection age with certain data, the clearing method is to initialize it again: age = make(map[string]int). If the map is no longer used later, you can directly: age=nil to achieve the purpose of clearing the data. But if it needs to be reused, make initialization must be done, otherwise nothing can be added to the nil map.

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)
}

Initialization of two-dimensional map

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

Leave a Reply

Your email address will not be published.

en_USEnglish