GO Map的初步使用

2022-08-25 13:21:33 字數 3029 閱讀 3667

張三:13910101201

李四:13801010134

map是go中的內建型別,它將乙個值與乙個鍵關聯起來。可以使用相應的鍵檢索值。

map 是一種無序的鍵值對的集合。map 最重要的一點是通過 key 來快速檢索資料,key 類似於索引,指向資料的值

map 是一種集合,所以我們可以像迭代陣列和切片那樣迭代它。不過,map 是無序的,我們無法決定它的返回順序,這是因為 map 是使用 hash 表來實現的,也是引用型別

使用map過程中需要注意的幾點:

可以使用內建函式 make 也可以使用 map 關鍵字來定義 map:

/* 宣告變數,預設 map 是 nil */

var map_variable map[key_data_type]value_data_type

/* 使用 make 函式 */

map_variable = make(map[key_data_type]value_data_type)

rating := map[string]float32
如果不初始化 map,那麼就會建立乙個 nil map。nil map 不能用來存放鍵值對

package main

import "fmt"

func main()

/* 檢視元素在集合中是否存在 */

captial, ok := countrycapitalmap["united states"]

/* 如果 ok 是 true, 則存在,否則不存在 */

if(ok)else

}

執行結果:

capital of france is paris

capital of italy is rome

capital of japan is tokyo

capital of india is new delhi

capital of united states is not present

delete(map, key) 函式用於刪除集合的元素, 引數為 map 和其對應的 key。刪除函式不返回任何值。

package main

import "fmt"

func main()

fmt.println("原始 map")

/* 列印 map */

for country := range countrycapitalmap

/* 刪除元素 */

delete(countrycapitalmap,"france");

fmt.println("entry for france is deleted")

fmt.println("刪除元素後 map")

/* 列印 map */

for country := range countrycapitalmap

}

執行結果:

原始 map

capital of france is paris

capital of italy is rome

capital of japan is tokyo

capital of india is new delhi

entry for france is deleted

刪除元素後 map

capital of italy is rome

capital of japan is tokyo

capital of india is new delhi

我們可以通過key獲取map中對應的value值。語法為:

map[key]
但是當key如果不存在的時候,我們會得到該value值型別的預設值,比如string型別得到空字串,int型別得到0。但是程式不會報錯。

所以我們可以使用ok-idiom獲取值,可知道key/value是否存在

value, ok := map[key]
示例**:

package main

import (

"fmt")

func main()

執行結果:

0 false

1 true

使用len函式可以確定map的長度。

len(map)  // 可以得到map的長度
與切片相似,對映是引用型別。當將對映分配給乙個新變數時,它們都指向相同的內部資料結構。因此,乙個的變化會反映另乙個。

示例**:

package main

import (

"fmt")

func main()

personsalary["mike"] = 9000

fmt.println("original person salary", personsalary)

newpersonsalary := personsalary

newpersonsalary["mike"] = 18000

fmt.println("person salary changed", personsalary)

}

執行結果:

original person salary map[steve:12000 jamie:15000 mike:9000]  

person salary changed map[steve:12000 jamie:15000 mike:18000]

map不能使用操作符進行比較。只能用來檢查map是否為空。否則會報錯:invalid operation: map1 == map2 (map can only be comparedto nil)

GO map的基本使用

var gomap map string string 定義gomap為map型別 gomap make map string string 初始化 key不存在為增加,key存在為修改 gomap a 加值 gomap b branana 加值 gomap a 重複增加 key相同 使用新的值覆蓋...

Go map的概念及三種使用方法

基本語法key 可以是什麼型別valuetype 可以是什麼型別注意 宣告是不會分配記憶體的,初始化需要 make 分配記憶體後才能賦值和使用。map的宣告和注意事項 var a map string string 在使用map前,需要先make make的作用就是給map分配資料空間 a make...

Qt UDP的初步使用

為了使用qt自帶的socket進行網路程式設計,先必須熟悉socket程式設計的原理,另外還需對qt一些基本類的操作比較熟悉。由於剛接觸不久,所以還是以看人家的 來學習。這次主要是學qt下udp的程式設計,且熟悉一些qt下 的編寫流程,所以本文參照的是 qt及qt quick開發實戰精解 一書中的第...