標籤:-- 空間 ack bbb 自動 增刪改 project [1] ring
// code_014_map_operator project main.gopackage mainimport ( "fmt")func DeleteMap(m map[int]string, key int) { delete(m, key) for k, v := range m { fmt.Printf("len(m)=%d, %d ----> %s\n", len(m), k, v) }}func main() { //賦值-->修改和追加 m1 := map[int]string{1: "ck_god", 2: "god_girl"} m1[1] = "xxx" m1[3] = "lily" //追加,go底層自動為map分配空間 fmt.Println(m1) m2 := make(map[int]string, 10) m2[0] = "aaa" m2[1] = "bbb" fmt.Println(m2) fmt.Println(m2[0], m2[1]) fmt.Println("") //遍曆 m3 := map[int]string{1: "ck_god", 2: "god_girl"} for k, v := range m3 { fmt.Printf("%d--->>>%s\n", k, v) } for k := range m3 { fmt.Printf("%d--->%s\n", k, m3[k]) } fmt.Println("") //擷取map的值 value, ok := m3[1] fmt.Println("value = ", value, ", ok = ", ok) value2, ok2 := m3[3] fmt.Println("value2 = ", value2, ", ok2 = ", ok2) fmt.Println("") //刪除 m4 := map[int]string{1: "ck_god", 2: "god_girl"} delete(m4, 2) //刪除key值為2的map for k, v := range m4 { fmt.Printf("%d--->%s\n", k, v) } fmt.Println("") //map作為參數傳遞 //在函數間傳遞映射並不會製造出該映射的一個副本,不是值傳遞,而是引用傳遞: m := map[int]string{1: "ck_god", 2: "god_girl", 3: "girl_angle"} DeleteMap(m, 3) for k, v := range m { fmt.Printf("len(m)=%d, %d ----> %s\n", len(m), k, v) }}
執行結果如下:
map[1:xxx 2:god_girl 3:lily]map[1:bbb 0:aaa]aaa bbb1--->>>ck_god2--->>>god_girl2--->god_girl1--->ck_godvalue = ck_god , ok = truevalue2 = , ok2 = false1--->ck_godlen(m)=2, 1 ----> ck_godlen(m)=2, 2 ----> god_girllen(m)=2, 1 ----> ck_godlen(m)=2, 2 ----> god_girl
Go中map的操作與使用(增刪改查)