本文主要是介绍Go-Maps,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
语法汇总
前面介绍的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 mapgoroutine 1 [running]:
panic(0x45a540, 0xc04203a000)C:/Go/src/runtime/panic.go:500 +0x1af
main.main()D:/examples/helloworld.go:13 +0x6f
exit status 2D:\examples>
*/
func main() {//x is a map of strings to ints. -- Reference: <<Introducing Go>> Slice, Map, P38 var x map[string]intx["first"] = 1
}
示例-make()
package main
import "fmt"/*
D:\examples>go run helloworld.go
x: 1 2D:\examples>
*/
func main() {x := make(map[string]int)x["first"] = 1 x["second"] = 2debug_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 2D:\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 mainimport "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: falsefmt.Println("value:", value, ", found:", found)
}
这篇关于Go-Maps的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!