Golang map进行操作,遍历

package main

import "fmt"

func main() {
	//map 操作
	city := make(map[string]string)
	//赋值 --增加-更新
	city["beijing"] = "北京"
	city["shanghai"] = "上海"
	city["shenzhen"] = "深圳"
	fmt.Println(city)			//map[beijing:北京 shanghai:上海 shenzhen:深圳]
	//更新
	city["beijing"] = "北京京"
	//查找
	k,ok := city["beijing"]
	if ok {
		fmt.Printf("有值--%s\n",k)		//有值--北京京
	} else {
		fmt.Println("没有值")
	}
	fmt.Println(city["beijing"])	//北京京
	//map的遍历
	for k,v := range city {
		fmt.Printf("key: %s value: %s\n",k,v)
	}
	//key: beijing value: 北京京
	//key: shanghai value: 上海
	//key: shenzhen value: 深圳
	fmt.Println(city)				//map[beijing:北京京 shanghai:上海 shenzhen:深圳]

	//删除
	delete(city,"beijing")		//map[shanghai:上海 shenzhen:深圳]
	fmt.Println(city)
	//直接重新分配空间==删除
	city = make(map[string]string)
	fmt.Println(city)				//map[]

	//双重map的遍历
	people := make(map[string]map[string]string)
	people["son"] = make(map[string]string)
	people["son"]["age"] = "12"
	people["son"]["name"] = "tt"
	people["son"]["addr"] = "beijing"

	people["guys"] = make(map[string]string)
	people["guys"]["age"] = "20"
	people["guys"]["name"] = "pp"
	people["guys"]["addr"] = "上海"

	//k1:  son
	//key2: age value2: 12
	//key2: name value2: tt
	//key2: addr value2: beijing
	//k1:  guys
	//key2: name value2: pp
	//key2: addr value2: 上海
	//key2: age value2: 20
	for k1,v1 := range people {
		fmt.Println("k1: ",k1)
		for k2,v2 :=range v1 {
			fmt.Printf("key2: %s value2: %s\n",k2,v2)
		}
	}

	fmt.Println("len(people): ",len(people))				//2
	fmt.Println("len(people-son): ",len(people["son"]))		//3
	fmt.Println("len(people-guys): ",len(people["guys"]))	//3
}

 

你可能感兴趣的:(golang)