Golang Maps 數據類型(map)


 

map介紹

- 介紹:

map 是在 Go 中將值(value)與鍵(key)關聯的內置類型。
通過相應的鍵可以獲取到值。

等同於python中的字典(dict)

 

- map 屬於引用類型:

map和 slices 類似,map 也是引用類型。
當 map 被賦值為一個新變量的時候,它們指向同一個內部數據結構。
因此,改變其中一個變量,就會影響到另一變量。

 

- map的相等性:

map 之間不能使用 == 操作符判斷,== 只能用來檢查 map 是否為 nil。

 

聲明map(創建map)

- 創建map的語法:make(map[Tkey]Tvalue)

  - 示例: make(map[string]int)

    - 創建一個 key為string類型,值為int類型的map

 

- 聲明map:

  - 語法: var 變量名 map[T-key]T-value

 

- 初始化:必須使用make初始化;

 

增刪改查

- 增加:

  - 初始化后,直接增加:

    - 示例:

package main

import (
    "fmt"
)

func main() {
    personSalary := make(map[string]int)
    personSalary["steve"] = 12000
    personSalary["jamie"] = 15000
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

// 打印內容:personSalary map contents: map[steve:12000 jamie:15000 mike:9000]

 

  - 初始化時增加:

    - 示例:

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int {
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

// 打印內容:personSalary map contents: map[steve:12000 jamie:15000 mike:9000]

 

- 刪除:

  - 語法:delete(map, key)   沒有返回值;

  - 示例:

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("map before deletion", personSalary)
    delete(personSalary, "steve")
    fmt.Println("map after deletion", personSalary)

}

// 打印內容:
    map before deletion map[steve:12000 jamie:15000 mike:9000]
    map after deletion map[mike:9000 jamie:15000]

 

- 獲取: 

  - 通過key直接取:

    - 語法: value, ok := 字典名["key"];ok: 當key存在的時候 返回 true,不存在返回 false,且 可以不寫;

    - 示例:

package main

import (
    "fmt"
)

func main() {
    dict := map[int]string{
        1: "Python",
        2: "Linux",
        3: "Golang",
    }
    fmt.Println(dict[1])
    // value := dict[2]
    value, ok := dict[2]
    // var value int
    // value, ok := dict[4]
    fmt.Println(value, ok)

}

 

  - 獲取map的長度:

    獲取 map 的長度使用 len 函數。

 

  - for range 循環

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("All items of a map")
    for key, value := range personSalary {
        fmt.Printf("personSalary[%s] = %d\n", key, value)
    }

}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM