中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

Go 語言Map(集合)

Map 是一種無序的鍵值對(duì)的集合。Map 最重要的一點(diǎn)是通過 key 來快速檢索數(shù)據(jù),key 類似于索引,指向數(shù)據(jù)的值。

Map 是一種集合,所以我們可以像迭代數(shù)組和切片那樣迭代它。不過,Map 是無序的,我們無法決定它的返回順序,這是因?yàn)?Map 是使用 hash 表來實(shí)現(xiàn)的。

定義 Map

可以使用內(nèi)建函數(shù) make 也可以使用 map 關(guān)鍵字來定義 Map:

/* 聲明變量,默認(rèn) map 是 nil */
var map_variable map[key_data_type]value_data_type

/* 使用 make 函數(shù) */
map_variable := make(map[key_data_type]value_data_type)

如果不初始化 map,那么就會(huì)創(chuàng)建一個(gè) nil map。nil map 不能用來存放鍵值對(duì)

實(shí)例

下面實(shí)例演示了創(chuàng)建和使用map:

實(shí)例

package main

import "fmt"

func main() {
? ? var countryCapitalMap map[string]string /*創(chuàng)建集合 */
? ? countryCapitalMap = make(map[string]string)

? ? /* map插入key - value對(duì),各個(gè)國家對(duì)應(yīng)的首都 */
? ? countryCapitalMap [ "France" ] = "巴黎"
? ? countryCapitalMap [ "Italy" ] = "羅馬"
? ? countryCapitalMap [ "Japan" ] = "東京"
? ? countryCapitalMap [ "India " ] = "新德里"

? ? /*使用鍵輸出地圖值 */
? ? for country := range countryCapitalMap {
? ? ? ? fmt.Println(country, "首都是", countryCapitalMap [country])
? ? }

? ? /*查看元素在集合中是否存在 */
? ? capital, ok := countryCapitalMap [ "American" ] /*如果確定是真實(shí)的,則存在,否則不存在 */
? ? /*fmt.Println(capital) */
? ? /*fmt.Println(ok) */
? ? if (ok) {
? ? ? ? fmt.Println("American 的首都是", capital)
? ? } else {
? ? ? ? fmt.Println("American 的首都不存在")
? ? }
}

以上實(shí)例運(yùn)行結(jié)果為:

France 首都是 巴黎
Italy 首都是 羅馬
Japan 首都是 東京
India  首都是 新德里
American 的首都不存在

delete() 函數(shù)

delete() 函數(shù)用于刪除集合的元素, 參數(shù)為 map 和其對(duì)應(yīng)的 key。實(shí)例如下:

實(shí)例

package main

import "fmt"

func main() {
? ? ? ? /* 創(chuàng)建map */
? ? ? ? countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New delhi"}

? ? ? ? fmt.Println("原始地圖")

? ? ? ? /* 打印地圖 */
? ? ? ? for country := range countryCapitalMap {
? ? ? ? ? ? ? ? fmt.Println(country, "首都是", countryCapitalMap [ country ])
? ? ? ? }

? ? ? ? /*刪除元素*/ delete(countryCapitalMap, "France")
? ? ? ? fmt.Println("法國條目被刪除")

? ? ? ? fmt.Println("刪除元素后地圖")

? ? ? ? /*打印地圖*/
? ? ? ? for country := range countryCapitalMap {
? ? ? ? ? ? ? ? fmt.Println(country, "首都是", countryCapitalMap [ country ])
? ? ? ? }
}

以上實(shí)例運(yùn)行結(jié)果為:

原始地圖
India 首都是 New delhi
France 首都是 Paris
Italy 首都是 Rome
Japan 首都是 Tokyo
法國條目被刪除
刪除元素后地圖
Italy 首都是 Rome
Japan 首都是 Tokyo
India 首都是 New delhi