maps 介紹

map 跟陣列(array)很像,只是他的key值不是用integer當作key值,而是採用字串(string)當key值。如:

map(
    john => 32
    mina => 28
    mike => 55
)

宣告方式:

map[keyType]valueType

使用map時的注意事項

  • key 值不能重複

簡單範例

package main
import "fmt"
func main() {
    var m map[string]int
    fmt.Println(m)
    fmt.Println("m == nil", m == nil)
}

// 輸出
map[]
m == nil true

通常map無法直接像上述方式使用。使用前必須先宣告:

m := make(map[keyType]valueType)

範例

package main
import "fmt"
func main() {
    age := make(map[string]int)
    age["mina"] = 28
    age["john"] = 32
    age["mike"] = 55
    fmt.Println("age of john", age["john"])
}

初始化就建立內容

package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    fmt.Println(age)
}

判斷map中是否有某個變數存在

package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    fmt.Println(age["mina"])
    fmt.Println(age["jessy"]).   // 不存在
}

// 輸出
28
0
  • 另一種判斷方式
value, ok := m[key]
  • 範例
package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    minaAge, minaOk := age["mina"]
    jessyAge, jessyOk := age["jessy"]
    fmt.Println(minaAge, minaOk)
    fmt.Println(jessyAge, jessyOk)
}

// 輸出
28 true
0 false

判斷map數量/長度

package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    fmt.Println("len(age) =", len(age))
}

刪除map元素

func delete(m map[Type]Type1, key Type)
  • 範例
package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    delete(age, "john")
    delete(age, "jessy")
    fmt.Println(age)
}

// 輸出
map[mina:28 mike:55]

存取 map 內資料

package main
import "fmt"
func main() {
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    for key, value := range age {
        fmt.Println(key, "=>", value)
    }
}

複製map內容

package main
import "fmt"
func main() {
    ages := make(map[string]int)
    age := map[string]int{
        "mina": 28,
        "john": 32,
        "mike": 55,
    }
    for key, value := range age {
        ages[key] = value
    }
    delete(ages, "john")
    fmt.Println("age", age)
    fmt.Println("ages", ages)
}