- map的声明方式有以下三种。
package main
import "fmt"
func main() {
//第一种声明方式
//声明map1是一个map类型,key是String,value是String
var myMap1 map[string] string
if myMap1 == nil {
fmt.Println("myMap1 是一个空map")
}
//在使用map前,需要先用make给map分配数据空间
myMap1 = make(map[string]string,10)
myMap1["one"] = "java"
myMap1["two"] = "c"
myMap1["three"] = "python"
fmt.Println("第一种方式", myMap1)
//第二种声明方式
myMap2 := make(map[int]string)
myMap2[1] = "navy"
myMap2[2] = "hj"
myMap2[3] = "liu"
fmt.Println("第二种方式", myMap2)
//第三种声明方式
myMap3 := map[string] string{
"one": "php",
"two": "c++",
"three": "python",
}
fmt.Println("第三种方式", myMap3)
}
- map的使用方式
map的增删改查
package main
import "fmt"
func main() {
cityMap :=make(map[string]string)
//添加
cityMap["China"] = "Beijing"
cityMap["Japan"] = "Tokyo"
cityMap["USA"] = "NewYork"
//遍历
for key,value := range cityMap {
fmt.Println("key = ",key)
fmt.Println("value = ",value)
}
//删除
delete(cityMap,"Japan")
//修改
cityMap["USA"] = "DC"
fmt.Println("-------------")
//遍历
for key, value := range cityMap {
fmt.Println("key = ",key)
fmt.Println("value = ",value)
}
}
文章来源:https://www.toymoban.com/news/detail-808610.html
- map的传参
package main
import (
"fmt"
)
func printMap(cityMap map[string]string) {
//cityMap 是一个引用传递
for key, value := range cityMap{
fmt.Println("key = ",key)
fmt.Println("value = ",value)
}
}
func changeValue(cityMap map[string] string) {
cityMap["England"] = "Lodndon"
}
func main() {
cityMap := make(map[string]string)
//添加
cityMap["China"] = "Beijing"
cityMap["Japan"] = "Tokyo"
cityMap["USA"] = "NewYork"
//遍历
printMap(cityMap)
//增加一个map
changeValue(cityMap)
fmt.Println("---------------")
//遍历
printMap(cityMap)
}
文章来源地址https://www.toymoban.com/news/detail-808610.html
到了这里,关于go语言(八)---- map的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!