【golang學習筆記】map

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

map學習筆記

golang中的map資料結構類似於java中的HashMap,能夠自動擴容,非並發安全,並且key是無序的。

關於為什麼在golang中map是內建的資料結構,可以見golang官方faq:https://golang.org/doc/faq#builtin_maps(國內可以使用這個網址訪問:https://golang.google.cn/doc/faq#builtin_maps)

map的基本用法

// map的聲明方式var map1 map[keytype]valuetype// 由於map是參考型別,因此必須顯示初始化,否則預設值是nilvar si map[string]intfmt.Println(si == nil) // truesi["monday"] = 1 //panic: assignment to entry in nil map//map的初始化方式主要有兩種:make方式和literal方式// 1.採用make分配記憶體//採用預設大小var map1 map[string]int = make(map[string]int)// 顯示指定大小,如果你要往map放入大量資料,最好在建立map的時候顯示指定map大小,// 否則會導致map頻繁擴容,影響效能var map1 map[string]int = make(map[string]int, 100)map1["age"] = 1// 2.literal方式初始化map1 := map[string]int{    "Monday": 1,    "Tuesday":2}map的常用操作:get、set、delete// 1.set:給map賦值map1["Wednesday"] = 3// 2.get:根據指定key從map中擷取value//根據key擷取map中的value,這裡如果指定key在map中不存在的話//會返回valuetype的"零值"(golang中的"零值"定義TODO)fmt.Println(map1["Wednesday"]) // print 3fmt.Println(map1["hello"]) // print 0 (0 是int類型的零值)//為了避免這種情況可以使用下面的指派陳述式進行測試v, ok := map1["Wednesday"]if v, ok := map1["Wednesday"]; ok { //process}// 3.delete:根據指定key從map中刪除值delete(map1, "Monday")// 4.通過len()擷取map當前的大小,不能對map使用cap()fmt.Println(len(map1))
  • map的key說明:官方文檔中闡述只要是任何定義了equal操作的類型都可以當做map的key,比如integers, floating point and complex numbers, strings, pointers, interfaces,channel、structs 和 arrays。而func、slice、map不能作為key,因為它們沒有定義equal操作。對於struct、interface和array來說,如果它們要作為key,必須它們包含的元素都可以作為key才行,如下測試代碼:
  type Person struct {name stringage int}type Person2 struct {name stringage intfriends []string}// struct作為map的key測試  var test map[Person]int = make(map[Person]int) // struct類型作為keytest[Person{"fuqiu", 20}] = 100fmt.Println(test[Person{"fuqiu", 20}]) // 輸出100   // interface作為map的key測試keyArray := [2]interface{}{1, "2"} var keyArrayMap map[[2]interface{}]int = make(map[[2]interface{}]int)keyArrayMap[keyArray] = 10000fmt.Println(keyArrayMap[keyArray]) // 輸出10000// interface{}類型作為key,但是其中包含func(){}元素,此時運行時報錯keyArray2 := [2]interface{}{1, func(){}} // 報錯資訊:panic: runtime error: hash of unhashable type func()var keyArrayMap2 map[[2]interface{}]int = make(map[[2]interface{}]int)keyArrayMap2[keyArray2] = 20000fmt.Println(keyArrayMap2[keyArray2])//使用包含了slice的struct作為key,因為slice不能作為map的key,因此運行時報錯var test2 map[Person2]int = make(map[Person2]int)test2[Person2{"fuqiu", 20, []string{"1", "2"}}] = 1000fmt.Println(test2[Person2{"fuqiu", 20, []string{"1", "2"}}]) // 報錯資訊:invalid map key type Person2
  • valuetype說明:可以是任意類型的;通過使用interface{}類型,我們可以儲存任意值
  • 在聲明的時候不需要知道 map 的長度,map 是可以動態增長的。
  • 未初始化的 map 的值是 nil

map一些需要注意的點

  • map 是參考型別
  • map的key是無序的(TODO:如何?有序)
  • 不要使用 new,永遠用 make 來構造 map,如果你錯誤的使用 new() 分配了一個引用對象,你會獲得一個Null 參考的指標,相當於聲明了一個未初始化的變數並且取了它的地址
mapCreated := new(map[string]float32)// 以下操作編譯器會報錯:invalid operation: mapCreated["key1"] (index of type *map[string]float32).mapCreated["key1"] = 4.5

map的一些提示

  • map[string]bool 來實現set的效果
  • map[string]func(){}

map的實現原理

TODO

參考資料

  • the-way-to-go
  • effective go

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.