Home >Backend Development >Golang >How to expand golang's hashmap
Define hashmap variables
Since go language is a strongly typed language, hashmap is also typed, specifically reflected in key and value The type must be specified. For example, if you declare a key as string and value as a map of string, you need to do this. (Recommended learning: go)
var m map[string]string // 声明一个hashmap,还不能直接使用,必须使用make来初始化 m = make(map[string]string) // 初始化一个map m = make(map[string]string, 3) // 初始化一个map并附带一个可选的初始bucket(非准确值,只是有提示意义) m := map[string]string{} // 声明并初始化 m := make(map[string]string) // 使用make来初始化
get,set,delete
m := map[string]int m["a"] = 1 fmt.Println(m["a"]) // 输出 1 // 如果访问一个不存在的key,返回类型默认值 fmt.Println(m["b"]) // 输出0 // 测试key是否存在 v, ok := m["b"] if ok { ... } // 删除一个key delete(m, "a") 迭代器 // 只迭代key for k := range m { ... } // 同时迭代key-value for k, v := range m { ... }
During the iteration process, the map can be deleted and updated. The rules are as follows:
The iteration is unordered, and the order is the same as the insertion. Irrelevant
Delete a key during the iteration process. No matter whether it has been traversed or not, it will not be traversed to
. During the iteration process, a key is added. It is not sure whether it can be traversed to
.Uninitialized maps can also be iterated
Others
The value of the map is not an address, which means that the syntax of &m["a"] is Illegal
len and cap can respectively obtain the number of kv and total capacity of the current map
The above is the detailed content of How to expand golang's hashmap. For more information, please follow other related articles on the PHP Chinese website!