当前位置:网站首页>【Golang】快速复习指南QuickReview(三)——map
【Golang】快速复习指南QuickReview(三)——map
2022-06-23 18:52:00 【DDGarfield】
学名:映射关系容器。
俗名:键值对key-value
map跟slice一样,依然是一个引用类型。
map
1.C#中的字典
根据map的特点,博主类比的是C#中字典Dictionary,同样都是键值对。
//定义 初始化
Dictionary<int, string> dic = new Dictionary<int, string>
{
{1,"学生"},
{2,"老师"},
{3,"家长"}
};
//新增
dic.Add(4, "校长");
//判断是否含key
if (dic.ContainsKey(1))
{
}
//判断是否含value
if (dic.ContainsValue("学生")) { }
//遍历字典
foreach (KeyValuePair<int, string> kv in dic)
{
}
//删除指定key的元素
dic.Remove(1);
//清空字典
dic.Clear();
2.Golang中的map
2.1 定义 初始化
make(map[KeyType]ValueType, [cap]),cap可选
testMap := make(map[int]string, 3)
testMap[1] = "学生"
testMap[2] = "老师"
testMap[3] = "家长"
fmt.Println(testMap)
map[1:学生 2:老师 3:家长]
2.2 遍历
使用for k,v:=range map{}遍历:
//遍历
for k, v := range testMap {
fmt.Println(k, v)
}
1 学生
2 老师
3 家长
2.3 删除
删除,使用内置函数delete()
func delete(m map[Key]Type, key Key)
//删除
delete(testMap, 1)
for k, v := range testMap {
fmt.Println(k, v)
}
3 家长
2 老师
2.4 重点来了
切片是一种类型,且使用频繁,切片就也能作为map的值value
var mapValueSlice = make(map[string][]string, 3)
var sc []string
sc = append(sc, "成都", "绵阳", "宜宾")
var sx = []string{"西安", "汉中", "榆林"}
mapValueSlice["四川"] = sc
mapValueSlice["陕西"] = sx
fmt.Println(mapValueSlice)
map[四川:[成都 绵阳 宜宾] 陕西:[西安 汉中 榆林]]
最后说一下,golang的源码读懂需要基础语法很牢固,后面的函数,方法接收者,指针,参数,返回值,通道等等,远远一看,中括号[]横飞,*,其实万变不离其宗,都是这些基础类型按照语义组合而成。
再次强调:这个系列并不是教程,如果想系统的学习,博主可推荐学习资源。
边栏推荐
猜你喜欢

硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件

Open source SPL redefines OLAP server

解读2022年度敏捷教练行业现状报告

LeetCode 260. 只出现一次的数字 III

Vprom notes

20省市公布元宇宙路线图

JDBC 在性能測試中的應用

「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能

Development of block hash quiz game system (DAPP)

NAACL 2022 Findings | 字节提出MTG:多语言文本生成数据集
随机推荐
The golden nine silver ten, depends on this detail, the offer obtains the soft hand!
Syntaxe des requêtes fédérées SQL (inline, left, right, full)
35 year old crisis? It has become a synonym for programmers
LeetCode 260. 只出现一次的数字 III
Online text entity extraction capability helps applications analyze massive text data
How to avoid the "black swan" incident in the gene field: a security war behind a preventive "recall"
Shell Scripting
Game asset reuse: a new way to find required game assets faster
Virtp4 notes
Not only Lei Jun, iqoo product manager, praised Qualcomm Xiaolong 8+: a new look
FlagAI飞智:AI基础模型开源项目,支持一键调用OPT等模型
测试的重要性及目的
Hotline salon issue 26 - cloud security session
Design of hardware switch with programmable full function rate limiter
GaussDB(DWS) 数据库智能监控运维服务-节点监控指标
Interview with Mo Tianlun | ivorysql wangzhibin - ivorysql, an Oracle compatible open source database based on PostgreSQL
Check four WiFi encryption standards: WEP, WPA, WPA2 and WPA3
在线文本实体抽取能力,助力应用解析海量文本数据
Programmable data plane (paper reading)
How to use the low code platform of the Internet of things for process management?