惜风不起、唯有努力!
golang中map增删改查与遍历简单使用

golang中map增删改查与遍历简单使用

/* map增删改查*/
func main(){
	map2 := make(map[string]string, 10)
	map2["num1"] = "上海"
	map2["num2"] = "北京"
	map2["num3"] = "杭州"
	//fmt.Println(map2)
	map2["num1"] = "天津"   //修改num1的V为天津
	fmt.Println(map2)

	delete(map2, "num2") //删除map2的key为num2,全部删除map中的key就重新定义map或者遍历删除
	fmt.Println(map2)

	val,ok := map2["num2"]     //判断num2是否有值,查。
	//fmt.Println(ok)
	if ok {
		fmt.Printf("key val is: %v\n",val)
	}else {
		fmt.Printf("not is key\n")
	}

	//map遍历
	for k, v := range map2 {
		fmt.Printf("k is: %v, v is: %v\n",k,v)
	}


	//map嵌套遍历
	stu_map := make(map[string]map[string]string)
	stu_map["mum_xues1"] = make(map[string]string, 3)
	stu_map["mum_xues1"]["name"] = "tom"
	stu_map["mum_xues1"]["sex"] = "男"
	stu_map["mum_xues1"]["addr"] = "杭州"

	stu_map["mum_xues2"] = make(map[string]string, 3)
	stu_map["mum_xues2"]["name"] = "aslis"
	stu_map["mum_xues2"]["sex"] = "男"
	stu_map["mum_xues2"]["addr"] = "北京"

	for k1,v1 := range stu_map {
		fmt.Printf("key1 is: %v\n",k1)

		for k2,v2 := range v1 {
			fmt.Printf("\t key2 is: %v, val2 is: %v\n", k2,v2)
		}
	}
	fmt.Printf("map 对数: %d\n",len(stu_map))
	fmt.Printf("map 对数: %d\n",len(stu_map["mum_xues2"]))
}

发表回复

您的电子邮箱地址不会被公开。