当前位置:网站首页>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
边栏推荐
- Click an EL checkbox to select all questions
- Use of node template engine
- Latex formula
- Matlab analytic hierarchy process to quickly calculate the weight
- 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
- JSX syntax rules
- Unity ECS dots notes
- LeetCode 1346、检查整数及其两倍数是否存在
- Solution: NPM err! code ELIFECYCLE npm ERR! errno 1
- 內網滲透之DOS命令
猜你喜欢
Preliminary understanding of cache elimination algorithm (LRU and LFU)
Some basic configurations in interlij idea
Latest investigation and progress of building intelligence based on sati
[stack and queue topics] - sliding window
LeetCode 74、搜索二维矩阵
After route link navigation, the sub page does not display the navigation style problem
[matlab 2016 use mex command to find editor visual studio 2019]
Case of the third day of go language development fresh every day project - news release system II
go-zero框架数据库方面避坑指南
[graph theory brush question-4] force deduction 778 Swimming in a rising pool
随机推荐
Automatically fill in body temperature and win10 task plan
Commande dos pour la pénétration de l'Intranet
PostgreSQL basic functions
GO語言開發天天生鮮項目第三天 案例-新聞發布系統二
bounding box iou
Resolve the error - error identifier 'attr_ id‘ is not in camel case camelcase
Identification of bolt points in aerial photography based on perception
Browser - learning notes
How do BIM swindlers cheat? (turn)
Learn to C language fourth day
Go language development Daily Fresh Project Day 3 Case - Press Release System II
Analysis of the relationship between generalized Bim and CAD under the current background
SQL: query duplicate data and delete duplicate data
打新债中签以后怎么办,网上开户安全吗
Psychological formula for converting RGB to gray value
Matlab: psychtoolbox installation
Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
Bracket matching -- [implementation of one-dimensional array]
GO语言开发天天生鲜项目第三天 案例-新闻发布系统二
Shanghai responded that "flour official website is an illegal website": neglect of operation and maintenance has been "hacked", and the police have filed a case