Go中map的操作與使用(增刪改查)

來源:互聯網
上載者:User

標籤:--   空間   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的操作與使用(增刪改查)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.