前往地圖備忘單

建立地圖

// define map
var m1 map[int]string

// instantiate map m1 = make(map[int]string)

// implict map instantiation m2 := make(map[int]string)

// map literal m3 := map[int]string{ 1: “One”, 9: “Nine” }

將商品添加到地圖

m := map[int]string{
    1:  "One",
    9:  "Nine"
}
m[10] = "Ten"

// m contains 1, 9, 10

從地圖查找項目

m := map[int]string{
    1:  "One",
    9:  "Nine"
}
item, ok := m[9]   //item is "Nine; ok is true if the
                    //key was found, false otherwise

從地圖上刪除項目

m := map[int]string{
    1:  "One",
    9:  "Nine"
}
delete(m, 9)
//m contains only the `1` item

刪除地圖上的所有內容

為指向地圖的變量分配一個新地圖:

m := map[int]string{
    1:  "One",
    9:  "Nine"
}
m = make(map[int]string) // m is an initialized, empty map

計算地圖中的項目

m := map[int]string{
    1:  "One",
    9:  "Nine"
}
l := len(m) // l == 2

將地圖的關鍵點切成片

keys := make([]string, 0, len(m))
for k := range m {
    keys = append(keys, k)
}

更多教程: