1. 程式人生 > 其它 >golang中map的crud操作

golang中map的crud操作

package main

import "fmt"

//map的增刪改查
func main() {

	school := make(map[string]string, 10)

	school["no1"] = "清華大學"
	//如果沒有key,則為增添,如果key已經存在,則為修改
	school["no1"] = "北京大學"   //修改
	school["no2"] = "清華大學"   //增添
	school["no5"] = "復旦大學"   //增添
	school["no6"] = "上海交通大學" //增添

	//map查詢
	val, catch := school["no2"]
	if catch {
		fmt.Printf("有no2 key值為%v\n", val)
	} else {
		fmt.Println("沒有no2")
	}
	//map刪除,delete(map,"key"),delete是一個內建函式,如果key存在,就刪除該key,如果key不存在,不操作,但是也不會報錯

	school["no3"] = "野雞大學" //新添
	fmt.Println(school)
	delete(school, "no3") //刪除key為no3的內容
	delete(school, "no4") //delete指定的key不存在,不會執行刪除操作,但是也沒有報錯
	fmt.Println(school)
	/*
		如果要刪除map所有的key,沒有一個專門的方法一次性刪除
		1.但是可以遍歷key逐個刪除
		2.或者map = make(),make一個新的空間,讓原來的成為垃圾,被gc回收
	*/
	//1.遍歷所有的key
	for key, value := range school {
		fmt.Printf("key=%v value=%v\n", key, value)
	}
	//2.直接make一個新的空間
	school = make(map[string]string)
	fmt.Println(school)

	//對較為複雜的map進行for-range遍歷
	id := make(map[string]map[string]string)
	id["no1"] = make(map[string]string, 3)
	id["no1"]["name"] = "派克"
	id["no1"]["sex"] = "男"
	id["no1"]["address"] = "比爾吉沃特"

	id["no2"] = make(map[string]string, 3)
	id["no2"]["name"] = "佐伊"
	id["no2"]["sex"] = "女"
	id["no2"]["address"] = "巨神峰"

	id["no3"] = make(map[string]string, 3)
	id["no3"]["name"] = "錘石"
	id["no3"]["sex"] = "男"
	id["no3"]["address"] = "暗影島"

	for key1, value1 := range id {
		fmt.Println("key1=", key1)
		for key2, value2 := range value1 {
			fmt.Printf("\t key2=%v value2=%v\n", key2, value2)
		}
		fmt.Println()
	}

	fmt.Println("id 有", len(id), "對 key")
}