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

Go语言学习之map (The way to go)

2017-04-01 10:48 896 查看
生命不止,继续Go go go. 今天与大家分享golang中的map。

map:

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

定义一个map并初始化,根据key获取value

colors := map[string]string{
"bird":  "blue",
"snake": "green",
"cat":   "black",
}

// Get color of snake.
c := colors["snake"]

// Display string.
fmt.Println(c)


通过==进行map赋值

names := map[int]string{}
// Add three pairs to the map in separate statements.
names[990] = "file.txt"
names[1009] = "data.xls"
names[1209] = "image.jpg"

// There are three pairs in the map.
fmt.Println(len(names))


通过delete删除

ids := map[string]int{}
ids["steve"] = 10
ids["mark"] = 20
ids["adnan"] = 30
fmt.Println(len(ids))

// Delete one key from it.
delete(ids, "steve")
fmt.Println(len(ids))


map的range遍历

animals := map[string]string{}
animals["cat"] = "Mittens"
animals["dog"] = "Spot"

// Loop over the map.
for key, value := range animals {
fmt.Println(key, "=", value)
}


获取map中所有的key

sizes := map[string]int{
"XL": 20,
"L":  10,
"M":  5,
}

// Loop over map and append keys to empty slice.
keys := []string{}
for key, _ := range sizes {
keys = append(keys, key)
}

// This is a slice of the keys.
fmt.Println(keys)


通过make进行构建

map是引用类型

lookup := make(map[string]int, 200)

// Use the new map.
lookup["cat"] = 10
result := lookup["cat"]
fmt.Println(result)


map作为函数参数

package main

import "fmt"

func PrintGreen(colors map[string]int) {
// Handle map argument.
fmt.Println(colors["green"])
}

func main() {
// This map has two string keys.
colors := map[string]int{
"blue":  10,
"green": 20,
}
// Pass map to func.
PrintGreen(colors)
}


按key进行排序

package main

import (
"fmt"
"sort"
)

func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"

// To store the keys in slice in sorted order
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)

// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}


最后献上代码:

// _Maps_ are Go's built-in [associative data type](http://en.wikipedia.org/wiki/Associative_array)
// (sometimes called _hashes_ or _dicts_ in other languages).

package main

import "fmt"

func main() {

// To create an empty map, use the builtin `make`:
// `make(map[key-type]val-type)`.
m := make(map[string]int)

// Set key/value pairs using typical `name[key] = val`
// syntax.
m["k1"] = 7
m["k2"] = 13

// Printing a map with e.g. `Println` will show all of
// its key/value pairs.
fmt.Println("map:", m)

// Get a value for a key with `name[key]`.
v1 := m["k1"]
fmt.Println("v1: ", v1)

// The builtin `len` returns the number of key/value
// pairs when called on a map.
fmt.Println("len:", len(m))

// The builtin `delete` removes key/value pairs from
// a map.
delete(m, "k2")
fmt.Println("map:", m)

// The optional second return value when getting a
// value from a map indicates if the key was present
// in the map. This can be used to disambiguate
// between missing keys and keys with zero values
// like `0` or `""`. Here we didn't need the value
// itself, so we ignored it with the _blank identifier_
// `_`.
_, prs := m["k2"]
fmt.Println("prs:", prs)

// You can also declare and initialize a new map in
// the same line with this syntax.
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: