分享
  1. 首页
  2. 文章

跟我一起学Golang:Map

· · 1051 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

概念

Golang一种内置结构,形式<key,value>,类似Java中的HashMap或者Python中的dict(字典)。其中key是可比较的,不能为slice,因为slice没有实现比较操作。另外需要注意一点就是map是引用类型,作为参数存在副作用。

操作以及例子

如何创建

使用make,语法格式:make(map[key-type]val-type)

可以在声明的时候初始化:map[key-type]val-type{key:value, ...}

如何修改

赋值:name[key]=val

删除: delete(name, key)

如何访问

直接使用下标:name[key]

带有校验型: val, ok := name[key], ok是false表示key对应的值不存在

例子:

// Maps are Go's built-in associative data type(sometimes called hashes or dicts in other languages)

package main

import "fmt"

func main() {

// to create an empty map, use the builtin make: make(map[key-type]val-type)

m := make(map[string]int)

// set key/value pairs using typical name[key]=val syntax

m["k1"] = 7

m["k2"] = 13

// Printing a map with e.g. fmt.Println will show all of its key/value pairs.

fmt.Println("map:", m)

// Get a value for a key with name[key]

v1 := m["k1"]

fmt.Println("v1:", v1)

// the builtin le returns the numbers of key/value pairs when called on a map

fmt.Println("len:", len(m))

// the builtin delete removes key/value pairs from a map

delete(m, "k2")

fmt.Println("map:", m)

/**

* the optional second return value when getting a value from a map

* indicates if the key was present in the map. This can be used to dismbiguate between missing keys

* and keys with zero values like 0 or "". Here we didn't need the value itself, so we ignored it with

* the blank identifer _.

**/

_, prs := m["k2"]

fmt.Println("prs:", prs)

if !prs {

fmt.Println("m[\"k2\"] is not exist.")

}

// you can also decalre and initialize a new map in the same line with this syntax

n := map[string]int{"foo": 1, "bar": 2}

fmt.Println("map:", n)

}

参考资料

https://golang.google.cn/doc/effective_go.html#maps

https://gobyexample.com/maps


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:

查看原文:跟我一起学Golang:Map

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1051 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏