Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场

Go-Maps

作者头像
李海彬
发布于 2018-03-27 01:59:55
发布于 2018-03-27 01:59:55
69900
代码可运行
举报
文章被收录于专栏:Golang语言社区Golang语言社区
运行总次数:0
代码可运行

语法汇总

前面介绍的array、slice都是顺序性列表,本节的map则是无序的。

这个map和C/C++/Java的map一样,在Python中称为字典/dictionary。但Golang中map的用法更符合脚本语言的特点,和Python很像。

涉及的主要语法点:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
var the_map map[string]int
the_map := make(map[string]int)
the_map := map[string]int {key:value, ...}
value, ok := the_map[key]    

示例-基本用法

下面这个例子给出了map的声明方法。但通常并不这么使用,因为这种声明之后必须要调用make()初始化之后才可赋值,与其这样,不如直接:= make()这种方式。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package main

/*
D:\examples>go run helloworld.go
panic: assignment to entry in nil map

goroutine 1 [running]:
panic(0x45a540, 0xc04203a000)
        C:/Go/src/runtime/panic.go:500 +0x1af
main.main()
        D:/examples/helloworld.go:13 +0x6f
exit status 2

D:\examples>
*/
func main() {
    //x is a map of strings to ints. -- Reference: <<Introducing Go>> Slice, Map, P38 
    var x map[string]int

    x["first"] = 1
}

示例-make()

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package main
import "fmt"

/*
D:\examples>go run helloworld.go
x:      1       2

D:\examples>
*/
func main() {
    x := make(map[string]int)

    x["first"] = 1 
    x["second"] = 2
    debug_map(x, "x:")
}

func debug_map(the_map map[string]int, msg string) {
    fmt.Print(msg, "\t")
    for _, item := range the_map {
        fmt.Print(item, "\t")
    }
    fmt.Println()
}

示例-make与初始化列表

这里所谓“初始化列表”借用C++的initialization list。在make的同时,给map指定key:value列表。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package main
import "fmt"

/*
D:\examples>go run helloworld.go
x:      1       2

D:\examples>
*/
func main() {
    x := map[string]int {
        "first" : 1,
        "second" : 2,
    }

    debug_map(x, "x:")
}

func debug_map(the_map map[string]int, msg string) {
    fmt.Print(msg, "\t")
    for _, item := range the_map {
        fmt.Print(item, "\t")
    }
    fmt.Println()
}

示例-判断元素是否存在

即便key不存在,调用the_map[the_key]的时候也不会抛出运行时异常。这和编译型语言、以及脚本语言Python都不一样。Go的处理方式更为优雅,写的代码行数也少。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package main
import "fmt"

/*
D:\examples>go run helloworld.go
a:  1
b:  0
value:  1 , exist:  true
Exist
value:  0 , exist:  false
Not exist.

D:\examples>
*/
func main() {
    x := map[string]int {
        "first" : 1,
        "second" : 2,
    }

    a := x["first"]
    b := x["third"]
    fmt.Println("a: ", a)
    fmt.Println("b: ", b)

    find_map(x, "first")
    find_map(x, "fourth")
}

func debug_map(the_map map[string]int, msg string) {
    fmt.Print(msg, "\t")
    for _, item := range the_map {
        fmt.Print(item, "\t")
    }
    fmt.Println()
}

func find_map(the_map map[string]int, key string) {
    value, exist := the_map[key]
    fmt.Println("value: ", value, ", exist: ", exist)

    if exist {
        fmt.Println("Exist")
    } else {
        fmt.Println("Not exist.")
    }
}

value

map的value可以是任何的数据,比如value本身也可以是map。这是Introducing Go中给出的例子,这里不再展开。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-05-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Rust vs Go:常用语法对比(十三)
题图来自 Go vs. Rust: The Ultimate Performance Battle
fliter
2023/09/05
1860
Rust vs Go:常用语法对比(十三)
go-redis使用入门
redis.NewClient(&redis.Options{}),其中Options是连接的配置,是一个结构体类型,以下是配置选项和说明
用户6297767
2023/11/21
5330
go-redis使用入门
golang 基础
考点:函数返回值命名 在函数有多个返回值时,只要有一个返回值有指定命名,其他的也必须有命名。如果返回值有有多个返回值必须加上括号;如果只有一个返回值并且有命名也需要加上括号;此处函数第一个返回值有sum名称,第二个未命名,所以错误。
golangLeetcode
2022/08/02
4360
Go-defer,panic,recover
defer 语法: defer function_name() 简单来讲,在defer所在函数执行完所有的代码之后,会自动执行defer的这个函数。 示例一(基本功能) package main import "fmt" /* D:\examples>go run helloworld.go first second D:\examples> */ func main() { defer second() first() } func first() { fmt.Printl
李海彬
2018/03/23
7610
golang面试题(带答案)[通俗易懂]
注:引用就是同一份,相当于起了一个别名,就是多起了一个名字而已。 在Go语言中的引用类型有:映射(map),数组切片(slice),通道(channel),方法与函数。 整型,字符串,布尔,数组在当作参数传递时,是传递副本的内存地址,也就是值传递。 2.下面代码输出什么,为什么
全栈程序员站长
2022/09/07
1.4K0
Rust vs Go:常用语法对比(二)
题图来自 Calling Rust code from Go - the Gambiarra way[1]
fliter
2023/09/05
3780
Rust vs Go:常用语法对比(二)
Go - 从0学习Go的第一课
2.下载编辑器,Atom在github上是开源的,官网:https://github.com/atom
stark张宇
2023/03/07
3230
Go Cheatsheet
go get will download the three-party lib to the GOPATH/src directory. The go search GOROOT first, then search GOPATH. But the denpendency only can keep one version, which will cause some conflict.
timerring
2025/02/12
680
Go语言-学习笔记
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
不务正业的猿
2022/03/23
7100
Go语言-学习笔记
Go-List
要点 Element表示链表的一个元素,List表示链表 访问元素的值: .Value list是双向链表,可以在指定的位置插入元素 初始化: New()。——和var x List 是等价的,但New()可读性更好。 元素个数: Len() 遍历: (1) Front()和Back()分别取链表的第一个元素和最后一个元素。如果为空,则返回nil。(2) Next()和Prev()分别返回当前元素的写一个或前一个元素。如果为空,则返回nil。 (3) 遍历整个链表的通用方法就是先Front(),然后依次Ne
李海彬
2018/03/23
7100
Go 延迟调用 defer 用法详解
defer (延迟调用)是 Go语言中的一个关键字,一般用于释放资源和连接、关闭文件、释放锁等。 和defer类似的有java的finally和C++的析构函数,这些语句一般是一定会执行的(某些特殊情况后文会提到),不过析构函数析构的是对象,而defer后面一般跟函数或方法。
一个会写诗的程序员
2022/05/13
1.2K0
Rust vs Go:常用语法对比(八)
题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[1] 141. Iterate in sequence over
fliter
2023/09/05
3450
Rust vs Go:常用语法对比(八)
Rust vs Go:常用语法对比(五)
Disjoint matches: overlapping occurrences are not counted.
fliter
2023/09/05
3010
Rust vs Go:常用语法对比(五)
golang 学习笔记
go语言完整的定义的变量的方法为 var 变量名 类型=值,var name string ="fuwei",可以简写为name:="fuwei"(这种只能在函数内使用,无法再包内使用),
付威
2021/05/06
1.1K0
Go函数及与函数相关机制 【Go语言圣经笔记】
函数可以让我们将一个语句序列打包为一个单元,然后可以从程序中其它地方多次调用。函数的机制可以让我们将一个大的工作分解为小的任务,这样的小任务可以让不同程序员在不同时间、不同地方独立完成。一个函数同时对用户隐藏了其实现细节(黑盒特性)。由于这些因素,对于任何编程语言来说,函数都是一个至关重要的部分。
Steve Wang
2021/12/06
1.2K0
Go语言基础速刷手册
这个“不务正业”的阿巩,今天冒着现学现卖的风险来和大家分享Go了,作为既具备C的理念又有Python 姿态的语言,怎么能不来试上一试呢!
才浅Coding攻略
2022/12/12
9110
Rust vs Go:常用语法对比(三)
题图来自When to use Rust and when to use Go[1]
fliter
2023/09/05
2780
Rust vs Go:常用语法对比(三)
Rust vs Go:常用语法对比(六)
res has type *http.Response. buffer has type []byte. It is idiomatic and strongly recommended to check errors at each step.
fliter
2023/09/05
2270
Rust vs Go:常用语法对比(六)
Rust vs Go:常用语法对比(一)
分 BTreeMap 和 HashMap,且都需要use进来; 前者无序,后者有序
fliter
2023/09/05
3180
Rust vs Go:常用语法对比(一)
Go 语言简介(上)— 语法
Hello World package main //声明本文件的package名 import "fmt" //import语言的fmt库——用于输出 func main() { fmt.Println("hello world") } 运行 你可以有两种运行方式, $go run hello.go hello world $go build hello.go $ls hello hello.go $./hello hello world 自己的package 你可以使用GOPATH环境变
李海彬
2018/03/22
1.2K0
相关推荐
Rust vs Go:常用语法对比(十三)
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验