当前位置:网站首页>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
边栏推荐
- Scripy tutorial - (2) write a simple crawler
- Recommend an open source free drawing software draw IO exportable vector graph
- Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
- Leetcode 994, rotten orange
- Syntax Error: TypeError: this. getOptions is not a function
- Numpy Index & slice & iteration
- After route link navigation, the sub page does not display the navigation style problem
- 【栈和队列专题】—— 滑动窗口
- LeetCode 20、有效的括号
- [PTA] l1-002 printing hourglass
猜你喜欢
ArcGIS JS version military landmark drawing (dovetail arrow, pincer arrow, assembly area) fan and other custom graphics

Modeling based on catiav6

【PTA】整除光棍

Install MySQL 5.0 under Linux 64bit 6 - the root password cannot be modified

High paid programmer & interview question series 91 limit 20000 loading is very slow. How to solve it? How to locate slow SQL?

vulnhub DC:1渗透笔记
![[graph theory brush question-4] force deduction 778 Swimming in a rising pool](/img/e3/a8cd9fc7773843e9e8ee6a6eba123f.png)
[graph theory brush question-4] force deduction 778 Swimming in a rising pool

Resolve the error - error identifier 'attr_ id‘ is not in camel case camelcase

Vscode download speed up

Imitation Baidu map realizes the three buttons to switch the map mode by automatically shrinking the bottom
随机推荐
Customize timeline component styles
How can matlab obtain the truncated image in trainingimagelabeler
【PTA】L1-006 连续因子
[PTA] l1-002 printing hourglass
An error occurs when the addressable assets system project is packaged. Runtimedata is null
2021-06-29 C escape character cancellation and use
高薪程序员&面试题精讲系列91之Limit 20000加载很慢怎么解决?如何定位慢SQL?
Thirty What are VM and VC?
The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
Mathematical modeling column | Part 5: MATLAB optimization model solving method (Part I): Standard Model
Leetcode 709, convert to lowercase
Introduction to standardization, regularization and normalization
DOS command of Intranet penetration
Linux64Bit下安装MySQL5.6-不能修改root密码
2021-09-02 unity project uses rider to build hot change project failure record of ilruntime
Recognition of high-speed road signs by Matlab using alexnet
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
Historical track data reading of Holux m1200-e Bluetooth GPS track recorder
Resolve the error - error identifier 'attr_ id‘ is not in camel case camelcase
LeetCode 994、腐烂的橘子