Go-Maps

时间:2022-05-05
本文章向大家介绍Go-Maps,主要内容包括语法汇总、示例-基本用法、示例-make()、示例-make与初始化列表、示例-判断元素是否存在、value、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

语法汇总

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