Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map声明和初始化 #6

Open
kevinyan815 opened this issue Aug 4, 2019 · 0 comments
Open

Map声明和初始化 #6

kevinyan815 opened this issue Aug 4, 2019 · 0 comments

Comments

@kevinyan815
Copy link
Owner

声明

map类型的变量声明方式如下:

var mapVar map[keyType]valueType

比如:

var map1 map[string]int

在声明的时候不需要知道 map 的长度,map 是可以动态增长的。map 是引用类型,所以未初始化的 map 的zero value是 nil。nil map没有键也不能向其添加键(写入nil map会引发允许时错误:panic: assignment to entry in nil map

初始化

map 是引用类型 ,内存用 make 方法来分配,如下三种方式是等效的

  • var mapCreated = make(map[string]float32)
  • mapCreated := make(map[string]float32)
  • mapCreated := map[string]float32{}
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是引用类型因此mapAssignedmapLit 的引用,对 mapAssigned 的修改也会影响到 mapLit 的值。
  • mapLit的初始话说明了 map literals 的使用方法: map 可以用 {key1: val1, key2: val2} 的描述方法来初始化,就像数组和结构体一样。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant