在 Go 中使用 Map 映射:创建映射:使用 make(map[keyType]valueType) 定义键值对的数据结构。添加键值对:使用 map[keyType]valueType[key] = value 添加键值对。检索值:使用 map[keyType]valueType[key] 获取与键关联的值。删除键值对:使用 delete(map[keyType]valueType, key) 删除键值对。迭代映射:使用 for key, value := range map[keyType]

如何在 Go 中使用 Map 映射
Map 是一种在 Go 中存储键值对的数据结构。它允许您将唯一键映射到其关联的值。
创建映射
要创建映射,可以使用以下语法:
立即学习“go语言免费学习笔记(深入)”;
<code class="go">map[keyType]valueType := make(map[keyType]valueType)</code>
其中:
keyType 是键的类型。valueType 是值的类型。例如,要创建一个映射字符串键映射到整数值的映射,可以使用以下代码:
<code class="go">userAges := make(map[string]int)</code>
添加键值对
要向映射中添加键值对,可以使用以下语法:
<code class="go">map[keyType]valueType[key] = value</code>
例如,要向 userAges 映射中添加 "John" 键映射到 30 的值,可以使用以下代码:
<code class="go">userAges["John"] = 30</code>
检索值
要从映射中检索值,可以使用以下语法:
<code class="go">value := map[keyType]valueType[key]</code>
如果映射中不存在给定的键,则 value 将为零值。
例如,要从 userAges 映射中检索 "John" 的值,可以使用以下代码:
<code class="go">age := userAges["John"]</code>
删除键值对
要从映射中删除键值对,可以使用以下语法:
<code class="go">delete(map[keyType]valueType, key)</code>
例如,要从 userAges 映射中删除 "John" 键值对,可以使用以下代码:
<code class="go">delete(userAges, "John")</code>
迭代映射
要遍历映射并迭代键值对,可以使用以下语法:
<code class="go">for key, value := range map[keyType]valueType {
// 在此执行操作
}</code>例如,要打印 userAges 映射中的所有键值对,可以使用以下代码:
<code class="go">for name, age := range userAges {
fmt.Println(name, age)
}</code>以上就是golang怎么用map映射的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号