首页
视频
资源
登录
原
Go Map声明、元素访问与遍历
4559
人阅读
2020/12/15 18:03
总访问:
2537855
评论:
0
收藏:
0
手机
分类:
Go
![go数据类型](https://img.tnblog.net/arcimg/hb/0dd243ae49394f12beed84237bfee1a3.jpg "go数据类型") >#Go Map声明、元素访问与遍历 [TOC] Map的声明 ------------ >Map的声明相当于其他语言的键值队,通常通过`map[key_type]value_type`的方式声明。如下举例: ```go m := map[string]int{"one": 1, "two": 2,"three": 3} m1 := map[string]int{} m1["one"] = 1 m2 := make(map[string]int, 10) //这里的10只能是cap不能是len ``` >我们可以通过下面的代码,对map做基本的了解 ```go package map_test import "testing" func TestInitMap(t *testing.T) { m1 := map[int]int{1: 1, 2: 4, 3: 9} t.Log(m1[2]) t.Logf("len m1=%d", len(m1)) m2 := map[int]int{} m2[4] = 16 t.Logf("len m2=%d", len(m2)) m3 := make(map[int]int, 10) // cap 不支持map键值对 t.Logf("len m3=%d", len(m3)) } ``` ![](https://img.tnblog.net/arcimg/hb/a2e71d7a93824c3f95b858d9b39ae787.png) 判断非空 ------------ >从刚刚的代码示例,我们知道了当不赋值时返回的不是nil而是0。当其键中值的本身为0时,我们该如何判断出它赋值还是没有赋值。接下来的案例就会解决这个问题。 ```go func TestAccessNotExistingKey(t *testing.T) { m1 := map[int]int{} t.Log(m1[1]) m1[2] = 0 t.Log(m1[2]) // 判断值存在还是空 。(v是值,ok是判断) if v, ok := m1[3]; ok { t.Logf("Key 3's value is %d", v) } else { t.Logf("Key 3 is not existing.") } } ``` ![](https://img.tnblog.net/arcimg/hb/2b02e9cc27284ef5a440363fd5e3261f.png) 遍历Map ------------ ```go func TestTravelMap(t *testing.T) { m1 := map[int]int{1: 1, 2: 4, 3: 9} for k, v := range m1 { t.Log(k, v) } } ``` ![](https://img.tnblog.net/arcimg/hb/7fd4c24c43ab44cba6a14782f670e995.png)
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}
尘叶心繁
这一世以无限游戏为使命!
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
.net后台框架
166篇
linux
17篇
linux中cve
1篇
windows中cve
0篇
资源分享
10篇
Win32
3篇
前端
28篇
传说中的c
4篇
Xamarin
9篇
docker
15篇
容器编排
101篇
grpc
4篇
Go
15篇
yaml模板
1篇
理论
2篇
更多
Sqlserver
4篇
云产品
39篇
git
3篇
Unity
1篇
考证
2篇
RabbitMq
23篇
Harbor
1篇
Ansible
8篇
Jenkins
17篇
Vue
1篇
Ids4
18篇
istio
1篇
架构
2篇
网络
7篇
windbg
4篇
AI
18篇
threejs
2篇
人物
1篇
嵌入式
2篇
python
13篇
HuggingFace
8篇
pytorch
9篇
opencv
6篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术