翻译自 https://gobyexample.com/
Go by Example
Go is an open source programming language designed for building simple, fast, and reliable software.
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.
Go by Example: Maps
map是golang内置关联数组类型,在其他语言中也被称为hash或字典。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package main
import "fmt"
func main() { m := make(map[string]int) m["k1"] = 7 m["k2"] = 13 fmt.Println("map:", m)
v1 := m["k1"] fmt.Println("v1:", v1)
fmt.Println("len:", len(m))
delete(m, "k2") fmt.Println("map:", m)
_, prs := m["k2"] fmt.Println("prs:", prs)
n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) }
|
1 2 3 4 5 6 7
| $ go run maps.go map: map[k1:7 k2:13] v1: 7 len: 2 map: map[k1:7] prs: false map: map[foo:1 bar:2]
|
原文链接:Go by Example: Maps