Hey, everyone, I am Zhou Ba. This time we will continue to learn the basics of Go map.
In the above-mentioned multiple articles, we Learned data types,arrays,Slicing etc. help us store data.
Especially slices, which can store multiple things and can be flexibly added, deleted, modified, and searched.
But slicing still has some inconveniences.
For example, a student has multiple information, such as Name,Height,Weight,Agewait.
If using slices, we may store it like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
According to the current knowledge, we can only go so far, and I can only think of this.
But there will be an obvious disadvantage, that is, we need to use the subscript to get the value or Modify the value .
And we have to count where the subscript of the value we want to modify is, which is relatively not that convenient.
map is called a dictionary in Python and Java It is also called map in PHP. Lists in PHP seem to have the function of map.
map is a key-value pair (key-value) storage structure, which is Unordered, internally implemented using hash, with high performance.
In Go, map is of type reference, and the memory map is as follows.
1 2 3 4 5 6 7 8 |
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
ps:关于这两种方式,哪个使用的多。
我的建议是,如果确定有多少个字段,就使用第一种,如果不确定多少个字段,是动态添加的,用第二种。
使用第二种要大概估算好容量,超过会触发自动扩容机制,可能会产生那么一丝丝的性能影响。
遍历map,通常只用一种方式for range
。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
只遍历key
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
删除map里面的值需要用到delete
。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
map在取值时,尽可能的判断一下是否key存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
上述我们学习了Go基础之map。如果在操作过程中有任何问题,记得下面讨论区留言,我们看到会第一时间解决问题。
The above is the detailed content of An article to help you understand the basics of Go language map. For more information, please follow other related articles on the PHP Chinese website!