2.6 Go語言中的Map

語言: CN / TW / HK

基本語法

Map屬於引用型(References),指向Hash Table,類似Python中的dict

基本定義

var mymap map[string]int

這樣定義出來的map實際上是一個nil,這裡不包含任何元素你也不能賦值,如果賦值的話會提示assignment to entry in nil map,所以需要定義並初始化。

var mymap map[string]int{
 key1: value1, ..., keyN: valueN}

來看以下的示例

package main

import "fmt"

func main() {
 
    monthdays := map[string]int{
 
        "Jan": 31, "Feb": 28, "Mar": 31,
        "Apr": 30, "May": 31, "Jun": 30,
        "Jul": 31, "Aug": 31, "Sep": 30,
        "Oct": 31, "Nov": 30, "Dec": 31,
    }
    fmt.Printf("monthdays = %v\n", monthdays)
}

注意:maps定義最後的逗號是必須的,如果沒有的話,編譯會報語法錯誤

./test_maps.go:10:40: syntax error: unexpected newline, expecting comma or }

使用make定義

在不確定初始值的情況下,可以使用make進行宣告,之後就可以進行賦值操作

mymap := make(map[Key_Type]Value_Type, initial_Capacity)
mymap := make(map[Key_Type]Value_Type)

來看以下示例,和上面的基本定義做一個對比。

package main

import "fmt"

func main() {
 
    var mymap map[int]string
    // panic: assignment to entry in nil map
    //mymap[1] = "one"
    fmt.Printf("var define map is %v\n", mymap)

    mymakemap := make(map[int]string)
    mymakemap[1] = "one"
    fmt.Printf("var define map is %v\n", mymakemap)
}

正如上面提到的,通過基本定義方式定義的map是無法賦值的,而通過make定義後返回的是一個初始化的map,所以可以被賦值。

常用操作

讀取Map值

這裡使用了for和range讀取雜湊值,與其他語言中的使用方法類似

package main

import "fmt"

func main() {
 
    monthdays := map[string]int{
 
        "Jan": 31, "Feb": 28, "Mar": 31,
        "Apr": 30, "May": 31, "Jun": 30,
        "Jul": 31, "Aug": 31, "Sep": 30,
        "Oct": 31, "Nov": 30, "Dec": 31,
    }

    year := 0
    // We ignore the key value, so use _ here, and we can not use _
    // as variable or you will get 'cannot use _ as value'
    for _, days := range monthdays {
 
        year += days
    }
    fmt.Printf("year = %d\n", year)

    // Test show loop values
    for month, days := range monthdays {
 
        fmt.Printf("current line key = %s, value = %d\n", month, days)
    }
}

輸出結果

year = 365
current line key = Jan, value = 31
current line key = Apr, value = 30
current line key = Oct, value = 31
current line key = Nov, value = 30
current line key = Dec, value = 31
current line key = Feb, value = 28
current line key = Mar, value = 31
current line key = May, value = 31
current line key = Jun, value = 30
current line key = Jul, value = 31
current line key = Aug, value = 31
current line key = Sep, value = 30

CURD操作

採用直接賦值的方式就可以對Map進行值更新,而判斷Map中是否包含key時,只需要增加一個變數ok,通過該變數的

package main

import "fmt"

func main() {
 
    monthdays := map[string]int{
 
        "Jan": 31, "Feb": 28, "Mar": 31,
        "Apr": 30, "May": 31, "Jun": 30,
        "Jul": 31, "Aug": 31, "Sep": 30,
        "Oct": 31, "Nov": 30, "Dec": 31,
    }

    // Add a new key in maps
    monthdays["newmonth"] = 100
    fmt.Printf("monthdays = %v\n", monthdays)

    // Update current key value
    monthdays["newmonth"] = 101
    fmt.Printf("monthdays = %v\n", monthdays)

    // Test key exsits
    //  It’s more Go like to name present “ok”, and use: v, ok := monthdays["Jan"].
    // In Go we call this the “comma ok” form.
    value, ok := monthdays["newmonth"]
    fmt.Printf("value = %d, present = %t\n", value, ok)

    // Test key not exists
    // NOTE(Ray): As we already define variable ok above, if the key is used again
    // we will get error: "no new variables on left side of :="
    // We can use new variable or just use = instead :=
    value, ok = monthdays["none"]
    fmt.Printf("value = %d, present = %t\n", value, ok)

    // Delete key
    delete(monthdays, "newmonth")
    fmt.Printf("monthdays = %v\n", monthdays)
}

輸出結果

monthdays = map[Apr:30 Aug:31 Dec:31 Feb:28 Jan:31 Jul:31 Jun:30 Mar:31 May:31 Nov:30 Oct:31 Sep:30 newmonth:100]
monthdays = map[Apr:30 Aug:31 Dec:31 Feb:28 Jan:31 Jul:31 Jun:30 Mar:31 May:31 Nov:30 Oct:31 Sep:30 newmonth:101]
value = 101, present = true
value = 0, present = false
monthdays = map[Apr:30 Aug:31 Dec:31 Feb:28 Jan:31 Jul:31 Jun:30 Mar:31 May:31 Nov:30 Oct:31 Sep:30]