var mapname map[keytype]valuetype
其中:package main import "fmt" func main() { var mapLit map[string]int //var mapCreated map[string]float32 var mapAssigned map[string]int mapLit = map[string]int{"one": 1, "two": 2} mapCreated := make(map[string]float32) mapAssigned = mapLit mapCreated["key1"] = 4.5 mapCreated["key2"] = 3.14159 mapAssigned["two"] = 3 fmt.Printf("Map literal at \"one\" is: %d\n", mapLit["one"]) fmt.Printf("Map created at \"key2\" is: %f\n", mapCreated["key2"]) fmt.Printf("Map assigned at \"two\" is: %d\n", mapLit["two"]) fmt.Printf("Map literal at \"ten\" is: %d\n", mapLit["ten"]) }输出结果:
Map literal at "one" is: 1
Map created at "key2" is: 3.14159
Map assigned at "two" is: 3
Map literal at "ten" is: 0
{key1: value1, key2: value2}
的格式来初始化 map ,就像数组和结构体一样。mapCreated := make(map[string]float)
等价于mapCreated := map[string]float{}
。mapCreated := new(map[string]float)
接下来当我们调用mapCreated["key1"] = 4.5
的时候,编译器会报错:
invalid operation: mapCreated["key1"] (index of type *map[string]float).
make(map[keytype]valuetype, cap)
例如:map2 := make(map[string]float, 100)
当 map 增长到容量上限的时候,如果再增加新的 key-value,map 的大小会自动加 1,所以出于性能的考虑,对于大的 map 或者会快速扩张的 map,即使只是大概知道容量,也最好先标明。noteFrequency := map[string]float32 { "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, "G0": 24.50, "A0": 27.50, "B0": 30.87, "A4": 440}
mp1 := make(map[int][]int) mp2 := make(map[int]*[]int)
本文链接:http://task.lmcjl.com/news/17071.html