跟我一起學(xué)Golang:Map

概念

Golang一種內(nèi)置結(jié)構(gòu),形式<key,value>,類似Java中的HashMap或者Python中的dict(字典)。其中key是可比較的,不能為slice,因?yàn)閟lice沒(méi)有實(shí)現(xiàn)比較操作。另外需要注意一點(diǎn)就是map是引用類型,作為參數(shù)存在副作用。

操作以及例子

如何創(chuàng)建

使用make,語(yǔ)法格式:make(map[key-type]val-type)

可以在聲明的時(shí)候初始化:map[key-type]val-type{key:value, ...}

如何修改

賦值:name[key]=val

刪除: delete(name, key)

如何訪問(wèn)

直接使用下標(biāo):name[key]

帶有校驗(yàn)型: val, ok := name[key], ok是false表示key對(duì)應(yīng)的值不存在

例子:

// Maps are Go's built-in associative data type(sometimes called hashes or dicts in other languages)

package main

import "fmt"

func main() {

? // to create an empty map, use the builtin make: make(map[key-type]val-type)

? m := make(map[string]int)

? // set key/value pairs using typical name[key]=val syntax

? m["k1"] = 7

? m["k2"] = 13

? // Printing a map with e.g. fmt.Println will show all of its key/value pairs.

? fmt.Println("map:", m)

? // Get a value for a key with name[key]

? v1 := m["k1"]

? fmt.Println("v1:", v1)

? // the builtin le returns the numbers of key/value pairs when called on a map

? fmt.Println("len:", len(m))

? // the builtin delete removes key/value pairs from a map

? delete(m, "k2")

? fmt.Println("map:", m)

? /**

? * the optional second return value when getting a value from a map

? * indicates if the key was present in the map. This can be used to dismbiguate between missing keys

? * and keys with zero values like 0 or "". Here we didn't need the value itself, so we ignored it with

? * the blank identifer _.

? **/

? _, prs := m["k2"]

? fmt.Println("prs:", prs)

? if !prs {

? ? fmt.Println("m[\"k2\"] is not exist.")

? }

? // you can also decalre and initialize a new map in the same line with this syntax

? n := map[string]int{"foo": 1, "bar": 2}

? fmt.Println("map:", n)

}

參考資料

https://golang.google.cn/doc/effective_go.html#maps

https://gobyexample.com/maps

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容