go語言 基礎系列 map基本操作

2021-08-31 03:26:43 字數 1831 閱讀 6767

map 是雜湊表的引用, 資料組+鍊錶的智慧型結合

【建立】

使用內建函式 :mymap:=make(map(string)int)

通過字面量賦值

mymap:=map[string]int
空map 為 map[string]int{}

【刪除】

使用內建函式delete

delete(mymap,"a")
delete原型如下

// the delete built-in function deletes the element with the specified key

// (m[key]) from the map. if m is nil or there is no such element, delete

// is a no-op.

func delete(m map[type]type1, key type)

【遍歷】

for k,v:=range mymap
【零值】

元素不存在  or  元素存在 但是值 為 零

【判斷元素是否在map中】

if t ,ok:=mymap["mykey"]; !ok
【map間的比較】

func equal(x, y map[string]int) bool 

for k, xv := range x

} return true

【構建set】

利用map中的key的唯一性 構建set

set:=make(map[string]bool)

y:=string(something)

if !set[y]

【構建slice型別的鍵值map】

首先通過乙個函式 實現 slice到字串的對映,然後賦值給map的鍵值

package main

import (

"fmt"

//"strings"

)//實現slice 到string的轉換

func k(list string) string

func main() ,

string,

string,

} fmt.println(x)

fmt.printf("%t", x)

m := make(map[string]int)

for _, b := range x

fmt.println("m is:")

fmt.println(m)

}

執行結果:

[[a b c] [aa bb cc] [aaa bbb]]

[3]stringb is: [a b c] ,type is string

newkey is: ["a" "b" "c"] ,type is string

b is: [aa bb cc] ,type is string

newkey is: ["aa" "bb" "cc"] ,type is string

b is: [aaa bbb] ,type is string

newkey is: ["aaa" "bbb"] ,type is string

m is:

map[["a" "b" "c"]:1 ["aa" "bb" "cc"]:1 ["aaa" "bbb"]:1]

即實現了  ["aaa" "bbb"]: 為key的場景。

Go語言基礎(十一)Map

map 是一種無序的鍵值對的集合。map 最重要的一點是通過 key 來快速檢索資料,key 類似於索引,指向資料的值。map 是一種集合,所以我們可以像迭代陣列和切片那樣迭代它。不過,map 是無序的,我們無法決定它的返回順序,這是因為 map 是使用 hash 表來實現的。func main m...

go語言基礎之map

go語言中提供的對映關係容器為map,其內部使用雜湊表hash實現 map map是一種無序的基於key value的資料結構,必須初始化才能使用 package main import fmt func main fmt.println map1 判斷某乙個值是否存在 返回兩個引數,1.返回的值 ...

Go語言基礎(四) map

三 練習題 go語言中提供的對映關係容器為map,其內部使用雜湊表 hash 實現。map是一種無序的基於key value的資料結構,go語言中的map是引用型別,必須初始化才能使用。map的定義 map keytype valuetype keytype 表示鍵的型別。valuetype 表示鍵...