go语言-map

luckyFang 2021年03月15日 14次浏览

基本使用

  • make(map[keyType]valueType)
package main

import "fmt"

func main()  {
	// map[keyType]valueType
	var m  map[string]string
	m= make(map[string]string,5)

	m["name"]="luckyFang"
	m["address"]="ShanXi"
	fmt.Printf("%v\n",m)

	person :=map[string]string{
		"name":"jack",
	}

	fmt.Printf("%v\n",person)


}

操作map

  • delete 删除元素
  • map 是引用传递的
package main

import "fmt"

func change(m map[string]int)  {
	m["ZhangSan"]=59
}


func main() {
	scoreMap:=make(map[string]int)
	// 添加元素
	scoreMap["LiHua"]=90
	scoreMap["XiaoMing"]=92
	scoreMap["LiLi"]=85
	fmt.Printf("%v\n",scoreMap)

	// 修改元素
	scoreMap["LiHua"]=60
	fmt.Printf("%v\n",scoreMap)
	// 删除元素
	delete(scoreMap,"LiLi")

	// map是引用传递
	change(scoreMap)

	// 遍历Map
	for name,score :=range scoreMap{
		fmt.Printf("name=%v,score=%d\n",name,score)
	}
}

map[LiHua:90 LiLi:85 XiaoMing:92]
map[LiHua:60 LiLi:85 XiaoMing:92]
name=LiHua,score=60
name=XiaoMing,score=92
name=ZhangSan,score=59