Go 分布式学习利器(6)-- Map
生活随笔
收集整理的這篇文章主要介紹了
Go 分布式学习利器(6)-- Map
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. Map的聲明
- 2. Map 元素訪問帶來的問題
- 3. Map 元素的遍歷
- 4. 通過Map 實現 函數對象(C++)
- 5. 通過Map實現一個簡單Set功能
1. Map的聲明
基本的幾種聲明和初始化方式如下:
m := map[string]int{"one":1, "two":2, "three":3}m := map[string]int{}m["one"] = 1m := make(map[string]int, 10 /*表示map結構的容量*/)這種方式一般對性能比較友好,因為不需要map結構的動態擴容帶來的開銷,直接將需要的容量分配好
測試函如下:
func TestMapInit(t *testing.T) {m1 := map[string]int{"one":1, "two":2, "three":3}t.Log(m1["two"])t.Log("len m1", len(m1))m2 := map[string]int{}t.Log("len m2", len(m2))m2["four"] = 4t.Log("len m2", len(m2))m3 := make(map[string]int, 10)t.Log("len m3", len(m3)) // 不支持cap 獲取map的容量
}
2. Map 元素訪問帶來的問題
我們定義一個m := map[int]int{}這樣的變量,那么該map的值已經被默認初始化為了0。
這樣的初始化方式 可能與我們實際的m[0]=0 產生沖突,所以Go語言也能夠像其他語言一樣主動判斷一個map的值是否為空,這里主要是通過之前的Go條件語句中的條件多次賦值的語法來進行的:
方式如下:
func TestJudgeMapResult(t *testing.T) {m1 := map[int]int{}t.Log(m1[0])//m1[0] = 0//t.Log(m1[0])if v,ok :=m1[0];ok{ // 條件多次賦值,v是int類型,表示m1[0]的值;ok 是bool類型,表示是否為空t.Log("m1[0] is not nil", v)} else {t.Log("m1[0] is nil")}
}
輸出如下:
=== RUN TestJudgeMapResultmap_test.go:23: 0map_test.go:30: m1[0] is nil
3. Map 元素的遍歷
基本語法 是通過 提到的for循環中的 for … range語法來進行的:
m1 := map[string]int{"one":1, "two":2, "three":3}
for k,v := range m1 {t.Log(k,v)
}
輸出如下:
=== RUN TestMapTravelmap_test.go:37: one 1map_test.go:37: two 2map_test.go:37: three 3
4. 通過Map 實現 函數對象(C++)
我知道C++的函數對象形態如下:
struct adder {adder(int n) : n_(n) {}int operator() (int x)const {return x + n_;}
private:int n_;
};auto add_3 = adder(3); // 初始化一個函數對象,為每一個傳入的數值加3
add_3(5); //表示為5 加3
這里可以通過Map,將函數作為value來更加方便的實現函數對象:
func TestMapImplementFunctionTemplate(t *testing.T) {m1 := map[int]func(op int) int{}m1[1] = func(op int) int {return op} // 等值 函數m1[2] = func(op int) int {return op*op} // 平方值 函數m1[3] = func(op int) int {return op*op*op} // 立方值 函數t.Log(m1[1](1), m1[2](2), m1[3](3))
}
5. 通過Map實現一個簡單Set功能
Go語言沒有天然的Set數據結構,不過這里我們可以通過Map實現很簡單的Set功能。
基本的Set功能如下:
- 元素具有唯一性
- 支持 添加,刪除,訪問元素個數,判斷元素是否存在的功能
簡單測試函數如下:
func TestMapImplementSet(t *testing.T) {Set := map[int]bool{} // 一個Set集合Set[1] = true // 集合的插入, 沒插入一個元素,保證一定將該元素的value置為true,即能保證集合的特性n := 3if Set[n]{t.Logf("%d is existing ",n )}else {t.Logf("%d is not existing. ",n )}Set[3] = truet.Log("len of Set ", len(Set)) // 集合的元素個數delete(Set,1) // 刪除map中的一個元素m := 1// 判斷該元素是否存在if Set[m]{t.Logf("%d is existing ",m)}else {t.Logf("%d is not existing. ",m )}
}
最終輸出如下:
=== RUN TestMapImplementSetmap_test.go:59: 3 is not existing. map_test.go:63: len of Set 2map_test.go:71: 1 is not existing.
--- PASS: TestMapImplementSet (0.00s)
總結
以上是生活随笔為你收集整理的Go 分布式学习利器(6)-- Map的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上海欢乐谷生日票怎么买
- 下一篇: Go 分布式学习利器(7)-- 字符串