当前位置:网站首页>go-map
go-map
2022-04-21 22:47:00 【The old chicken still needs to work hard】
go-map
Introduce
-
map yes key-value data structure , Also known as fields or associative arrays . A collection similar to other programming languages .
-
Basic grammar :
var map Variable name map[keyType]valueTypekeyType:golang Medium map Of key There can be many types :bool、 Numbers 、string、 The pointer 、channel、 It can also contain only the first few types of interfaces 、 Structure 、 Array
Usually int and string
-
slice,map also function Can not be , Because these don't work == To judge
-
valueType The type and key Basically similar
It's usually numbers 、string、map、struct
-
map Be sure to use the sign make Allocate space
-
map Of key Can't repeat , If you repeat , It will cover
-
map Of value Can be repeated
-
map Of key-value disorder
-
make mapping : The creation of the initial allocation depends on size, But the resulting mapping length is 0.size It can be omitted , In this case, a Small starting size .
func main() {
var map1 map[string]int = make(map[string]int) // Need to be make Allocate space , Otherwise it won't work
fmt.Printf("map1: %v\n", map1) // map1: map[]
fmt.Printf("&map1: %p\n", &map1) // &map1: 0xc0000b6010
map1["tom"] = 22
map1["jack"] = 33
map1["tom"] = 33
fmt.Printf("map1: %v\n", map1) // map1: map[jack:33 tom:33] key No repetition , And disorder
}
Three uses
- Declare first and then make
- Both statement and make
- Statement + assignment
func main() {
// 1. Declare before assign
var map1 map[string]int
map1 = make(map[string]int)
map1["tom"] = 22
map1["jack"] = 33
fmt.Printf("map1: %v\n", map1) // map1: map[jack:33 tom:22]
// 2. Statement +make
var map2 map[string]int = make(map[string]int)
map2["beijing"] = 1
map2["shanghai"] = 2
map2["dalian"] = 5
fmt.Printf("map2: %v\n", map2) // map2: map[beijing:1 dalian:5 shanghai:2]
// 3. Statement + assignment
var map3 map[string]int = map[string]int{
"beijing": 1,
"shanghai": 2,
"shenzhen": 3, // , Can't save
}
map3["xiongan"] = 4
// map3 := map[string]int{"beijing": 1, "shanghai": 2, "shenzhen": 3}
fmt.Printf("map3: %v\n", map3) // map3: map[beijing:1 shanghai:2 shenzhen:3 xiongan:4]
}
studentMap := make(map[string]map[string]string)
studentMap["student1"] = make(map[string]string)
studentMap["student1"]["name"] = "tom"
studentMap["student1"]["sex"] = "man"
studentMap["student1"]["address"] = "beijing"
studentMap["student1"]["tel"] = "123456789"
studentMap["student2"] = make(map[string]string)
studentMap["student2"]["name"] = "jack"
studentMap["student2"]["sex"] = "women"
studentMap["student2"]["address"] = "shanghai"
studentMap["student2"]["tel"] = "123123123"
fmt.Printf("studentMap: %v\n", studentMap)
fmt.Printf("studentMap[\"student1\"]: %v\n", studentMap["student1"])
fmt.Printf("studentMap[\"student2\"]: %v\n", studentMap["student2"])
fmt.Printf("studentMap[\"student1\"][\"name\"]: %v\n", studentMap["student1"]["name"])
crud operation
func main() {
var map1 map[string]int = make(map[string]int)
// 1. Add and modify
// 1.1 add to key Does not exist is to add
map1["tom"] = 22
map1["jack"] = 33
fmt.Printf("map1: %v\n", map1) // map1: map[jack:33 tom:22]
// 1.2 modify key To exist is to add
map1["jack"] = 66
fmt.Printf("map1: %v\n", map1) // map1: map[jack:66 tom:22]
// 2. Delete Built in functions delete(map, key)
delete(map1, "tom")
fmt.Printf("map1: %v\n", map1) // map1: map[jack:66]
delete(map1, "tom") // When it doesn't exist , No errors reported
// 3. Empty map
// 3.1 Traverse and delete one by one
for k := range map1 {
delete(map1, k)
}
// 3.2 Direct to map Open up a new space , make
map1 = make(map[string]int)
// 4. lookup The first return value is Corresponding value value, The second return value is , Whether to find , If found as true Otherwise false
val, findres := map1["no"]
if findres {
fmt.Printf("val: %v\n", val)
} else {
fmt.Println("no find")
}
}
Traverse
func main() {
// map Traverse
var people map[string]int = map[string]int{
"tom": 22, "jack": 33, "luxy": 44}
// 1. Global traversal
for k, v := range people {
fmt.Printf("%v: %v\t", k, v) // tom: 22 jack: 33 luxy: 44
}
fmt.Println("")
// 2. Traverse only key and obtain key The section of
keys := make([]string, 0, len(people))
for k := range people {
keys = append(keys, k)
fmt.Printf("k: %v\n", k)
}
// k: tom
// k: jack
// k: luxy
// 3. Built in functions len obtain map The length of
fmt.Printf("len(people): %v\n", len(people)) // len(people): 3
}
section
func main() {
var people []map[string]string = make([]map[string]string, 1)
var people1 map[string]string = make(map[string]string)
people1["name"] = "tom"
people1["age"] = "22"
people1["address"] = "shanghai"
people = append(people, people1)
var people2 map[string]string = make(map[string]string)
people2["name"] = "jack"
people2["age"] = "33"
people2["address"] = "beijing"
people = append(people, people2)
people[0] = make(map[string]string)
people[0]["name"] = "lucy"
people[0]["age"] = "44"
people[0]["address"] = "shenzhen"
// people: [map[address:shanghai age:22 name:tom] map[address:beijing age:33 name:jack]]
fmt.Printf("people: %v\n", people)
for index, val := range people {
fmt.Printf("index: %v\n", index)
// fmt.Printf("val: %v\n", val)
for k, v := range val {
fmt.Printf("\t %v: %v \n", k, v)
}
}
// index: 0 val: map[address:shanghai age:22 name:tom]
// index: 1 val: map[address:beijing age:33 name:jack]
/* index: 0 age: 22 address: shanghai name: tom index: 1 name: jack age: 33 address: beijing */
}
Sort
- golang There is no specific method for map Of key Sort
- golang Medium map Default is out of order , Note that it is not stored in the order of addition , The output of each iteration is different
- golang Medium map Sort , First of all key Sort , And then according to key Value traverses the input
import (
"fmt"
"sort"
)
func main() {
var numMap map[int]int = make(map[int]int)
numMap[3] = 33
numMap[1] = 11
numMap[4] = 44
numMap[2] = 22
numMap[5] = 55
fmt.Printf("numMap: %v\n", numMap)
// 1. First the map Of key Put it into the slice
// 2. Sort the slices
// 3. Traversing slices . according to key To input map value
keys := make([]int, 0, len(numMap))
for k := range numMap {
keys = append(keys, k)
}
sort.Ints(keys)
fmt.Printf("keys: %v\n", keys) // keys: [1 2 3 4 5]
for _, v := range keys {
fmt.Printf("key: %v value: %v\n", v, numMap[v])
// key: 1 value: 11
// key: 2 value: 22
// key: 3 value: 33
// key: 4 value: 44
// key: 5 value: 55
}
}
matters needing attention
-
map Is a reference type , The passing mechanism of reference type , Receive... In a function map, After modification , Will directly modify the original map
func main() { map1 := make(map[int]int) map1[1] = 11 map1[3] = 33 test(map1) fmt.Printf("map1: %v\n", map1) // map1: map[1:111 2:222 3:33] } func test(map1 map[int]int) { map1[1] = 111 map1[2] = 222 } -
map After the capacity expansion of , Again to map Add elements , It will automatically expand , It won't happen panic, in other words map Can dynamically increase key value pairs
-
map Of value It's also used a lot struct type , Better for managing complex data ( Than the front value It's a map Better ), such as value yes Student Structure
func main() {
studentMap := make(map[int]student)
studentMap[1] = student{
"tom", 11, "beijing"}
studentMap[2] = student{
"jack", 22, "shanghai"}
studentMap[3] = student{
"lucy", 33, "shenzhen"}
fmt.Printf("studentMap: %v\n", studentMap)
for k, s := range studentMap {
fmt.Printf("k: %v ", k)
fmt.Printf("s.name: %v ", s.name)
fmt.Printf("s.age: %v ", s.age)
fmt.Printf("s.address: %v\n", s.address)
}
}
type student struct {
name string
age int
address string
}
Case study
func main() {
var userMap map[string]map[string]string = make(map[string]map[string]string)
name := "tom"
modifyUser(userMap, name)
fmt.Printf("userMap: %v\n", userMap)
// userMap: map[tom:map[nickname:nickname pwd:123456]]
modifyUser(userMap, name)
fmt.Printf("userMap: %v\n", userMap)
// userMap: map[tom:map[nickname:nickname pwd:888888]]
}
func modifyUser(users map[string]map[string]string, name string) {
v, findres := users[name]
if findres {
v["pwd"] = "888888"
} else {
v = make(map[string]string)
v["nickname"] = "nickname"
v["pwd"] = "123456"
users[name] = v
}
}
版权声明
本文为[The old chicken still needs to work hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212242256201.html
边栏推荐
- 深入理解mysql各种锁
- 事件分发机制Android,大厂Android面试总结 详细解答
- Module 3: Outsourcing student management system - architecture design document
- Unlock openharmony technology day! The annual event is about to open!
- 【中南林业科技大学】【陈】第六周创新题素数
- D:MATLAB.N个实用技巧-MATLAB中文论坛精华总结
- 2022年监理工程师考试基本理论与相关法规练习题及答案
- YARN线上动态资源调优
- Sorting methods (8 kinds) detailed explanation 6 - quick sorting
- Outsourcing student management system detailed architecture design document
猜你喜欢

循环队列与扩容

OpenCV中的Core组件——输入输出XML, YAML(12)

将模型训练外包真的安全吗?新研究:外包商可能植入后门,控制银行放款

【FPGA的基础学习-------OV7725摄像头模块】

Oracle database 22c insight:_ kgl_ Large_ heap_ assert_ Threshold automatic and manual adjustment

Unlock openharmony technology day! The annual event is about to open!

Image processing in opencv -- an example of discrete Fourier transform (11)

4. MySQL workbench create access user

openCV——直方图处理

L3-1 then don't worry (30 points) - pit point, test point analysis
随机推荐
Deploying wikijs using Helm
L1-062 lucky lottery (15 points)
Black box test - data reading and output mode
模块三:外包学生管理系统-架构设计文档
L1-064 估值一亿的AI核心代码 (20 分)
Detailed explanation of MySQL concurrency parameter adjustment
OpenCV中的图像处理——离散傅里叶变换实例(11)
[Central South University of forestry science and technology] [Chen] sixth week innovation question prime
Analysis on the underlying principle of MySQL transaction and isolation level
Wechat applet custom tabbar
事件分发机制流程图,程序员翻身之路
Analysis and interpretation of specialized special new agency and specialized special new agency policy, with a subsidy of RMB 200000-1 million
日撸代码300行学习笔记 Day 46
2022 intermediate accounting title examination accounting practice exercises and answers
1. MySQL workbench 8.0 installation
[summary of some tips and shortcut keys in MATLAB]
L1-063 吃鱼还是吃肉 (10 分)
POI Point of interesting.
OS Experiment 3 [process communication]
Why: uncaught referenceerror: effect is not defined