您的位置:首页 > 编程语言 > Go语言

Go-Maps

2016-08-31 14:17 134 查看

语法汇总

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

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

涉及的主要语法点:

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()这种方式。

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()

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列表。

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的处理方式更为优雅,写的代码行数也少。

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中给出的例子,这里不再展开。

删除元素&判断是否存在

package main

import "fmt"

func main() {
values := make(map[int]string)
values[1] = "One"
values[2] = "two"
values[3] = "three"

//values: map[1:One 2:two 3:three]
fmt.Println("values:", values)

delete(values, 2)

//values: map[1:One 3:three]
fmt.Println("values:", values)

value, found := values[2]

//value:  , found: false
fmt.Println("value:", value, ", found:", found)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Go maps 映射