当前位置:网站首页>go map
go map
2022-04-23 20:39:00 【baboon_ chen】
go map characteristic
1、map Normal operation .
Map Stored is an unordered collection of key value pairs , lead ⽤ type , Hashtable . The key has to be ⽀ Hold the equality operator (==、!=) type ,⽐ Such as number、string、pointer、array、struct, And corresponding interface. Values can be any type , There is no limit to .
Example :
unc test1() {
// 1、 initialization
m1 := make(map[int]string, 1000) // 1000 Express map Maximum storage key_value The number of , Beyond , Need to reallocate memory
m2 := map[string]int{
"a": 1,
}
// 2、 Judge key Whether there is
if val, ok := m2["a"]; ok {
fmt.Println(val)
}
// 3、 Access does not exist key
fmt.Println(m2["b"]) // return value Default initial value of type
// 4、 Add or modify
m2["b"] = 1
// 5、 Delete key
delete(m2, "c") // If key non-existent , No mistakes
// 6、 Get the number of key value pairs
fmt.Println(len(m1)) // cap Invalid
// 7、 Traverse
for k, v := range m2 {
fmt.Println(k, v) // Return in random order , It's different every time
}
for k := range m2 {
fmt.Println(k)
}
for _, v := range m2 {
fmt.Println(v)
}
}
2、 How to traverse in sequence map? take key Sort , And then according to key Go find value.
Example :
func test2() {
m := make(map[string]int, 32)
rand.Seed(time.Now().UnixNano())
keySlice := []string{
}
for i := 0; i < 10; i++ {
key := fmt.Sprintf("stu_%d", i)
m[key] = rand.Intn(100)
keySlice = append(keySlice, key)
}
fmt.Println("before sort, the map is:")
for k, v := range m {
fmt.Println(k, v)
}
fmt.Println("\nafter sort:")
sort.Strings(keySlice)
for _, v := range keySlice {
fmt.Println(v, m[v])
}
}
Output :
before sort, the map is:
stu_3 99
stu_4 34
stu_6 9
stu_9 92
stu_2 37
stu_8 92
stu_7 79
stu_0 88
stu_5 41
stu_1 69
after sort:
stu_0 88
stu_1 69
stu_2 37
stu_3 99
stu_4 34
stu_5 41
stu_6 9
stu_7 79
stu_8 92
stu_9 92
3、 from map What is retrieved from the is ⼀ individual value Temporary copy , Changes to its members are meaningless .
Example :
type user struct{
name string }
m := map[int]user{
// When map Due to expansion ⽽ When hashing again , The storage location of each key value item will send ⽣ change . therefore ,map
1: {
"user1"}, // Designed to not addressable. similar m[1].name This expectation passes through the original value
} // Pointer to modify the name of the member ⾏ by ⾃ However, it will be banned ⽌.
m[1].name = "Tom" // Error: cannot assign to m[1].name
Correct modification method :
// Method 1
u := m[1] // m[1] Returns the structure of a value copy
u.name = "Tom"
m[1] = u // Replace value.
// Method 2
m2 := map[int]*user{
// m2[1] Return pointer copy
1: &user{
"user1"},
}
m2[1].name = "Jack" // Returns a copy of the pointer . It is allowed to modify the original object through the pointer .
4、 You can safely delete key values during iteration . However, if there are new operations during the period , There will be an exception .
Example :
func test3() {
m := map[int]string{
1: "zhou",
2: "wu",
3: "zheng",
4: "wang",
}
fmt.Printf("before delete, the map is:%v\n", m)
for k := range m {
delete(m, k)
}
fmt.Printf("after delete, the map is:%v\n", m)
m2 := map[int]string{
1: "zhou",
2: "wu",
3: "zheng",
4: "wang",
}
fmt.Printf("\nbefore delete, the m2 is:%v\n", m2)
for k := range m2 {
m2[k+k] = "add new"
delete(m2, k)
}
fmt.Printf("after delete, the m2 is:%v\n", m2)
}
Output :
before delete, the map is:map[1:zhou 2:wu 3:zheng 4:wang]
after delete, the map is:map[]
before delete, the m2 is:map[1:zhou 2:wu 3:zheng 4:wang]
after delete, the m2 is:map[4:add new 6:add new 16:add new]
5、 map_slice、 slice_map
Example :
func sliceMap() {
s := make([]map[string]int, 4)
s[0] = make(map[string]int, 16)
s[0]["stu_01"] = 50
s[0]["stu_02"] = 60
s[0]["stu_01"] = 70
for i, v := range s {
fmt.Printf("s[%d] = %#v\n", i, v)
}
}
func mapSlice() {
m := make(map[string][]int, 4)
key := "stu_01"
if _, ok := m[key]; !ok {
m[key] = make([]int, 0, 8)
}
m[key] = append(m[key], 100)
m[key] = append(m[key], 200)
m[key] = append(m[key], 300)
for k, v := range m {
fmt.Println(k, v)
}
}
Output :
s[0] = map[string]int{
"stu_01":70, "stu_02":60}
s[1] = map[string]int(nil)
s[2] = map[string]int(nil)
s[3] = map[string]int(nil)
stu_01 [100 200 300]
版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351399.html
边栏推荐
- Installation and use of NVM
- 【PTA】L2-011 玩转二叉树
- Thirty What are VM and VC?
- [matlab 2016 use mex command to find editor visual studio 2019]
- Tensorflow 2 basic operation dictionary
- Syntax Error: TypeError: this. getOptions is not a function
- CONDA environment management command
- The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
- [stack and queue topics] - sliding window
- LeetCode 116. Populate the next right node pointer for each node
猜你喜欢

Go zero framework database avoidance Guide

How to use PM2 management application? Come in and see

LeetCode 542、01 矩阵

Three. Based on ply format point cloud voxel model JS upload interface writing

Identifier CV is not defined in opencv4_ CAP_ PROP_ FPS; CV_ CAP_ PROP_ FRAME_ COUNT; CV_ CAP_ PROP_ POS_ Frames problem

Matlab: psychtoolbox installation

How to protect ECs from hacker attacks?

Flex layout

Resolve the eslint warning -- ignore the warning that there is no space between the method name and ()

缓存淘汰算法初步认识(LRU和LFU)
随机推荐
LeetCode 542、01 矩阵
Shanghai a répondu que « le site officiel de la farine est illégal »: l'exploitation et l'entretien négligents ont été « noirs » et la police a déposé une plainte
Mathematical modeling column | Part 5: MATLAB optimization model solving method (Part I): Standard Model
How to protect ECs from hacker attacks?
Go language development Daily Fresh Project Day 3 Case - Press Release System II
Scripy tutorial - (2) write a simple crawler
Numpy Index & slice & iteration
三十.什么是vm和vc?
How do BIM swindlers cheat? (turn)
SQL gets the latest record of the data table
Numpy mathematical function & logical function
16MySQL之DCL 中 COMMIT和ROllBACK
Bash script learning -- for loop traversal
缓存淘汰算法初步认识(LRU和LFU)
6-5 string - 2 String copy (assignment) (10 points) the C language standard function library includes the strcpy function for string copy (assignment). As an exercise, we write a function with the sam
GO語言開發天天生鮮項目第三天 案例-新聞發布系統二
Solve the Chinese garbled code of URL in JS - decoding
堡垒机、跳板机JumpServer的搭建,以及使用,图文详细
上海回应“面粉官网是非法网站”:疏于运维被“黑”,警方已立案
LeetCode 994、腐烂的橘子