package mainimport("encoding/json""fmt"cmap "github.com/orcaman/concurrent-map""github.com/prometheus/common/log""strconv")type Animal struct{name string}funcmain(){m := cmap.New()// cmap.ConcurrentMapelephant := Animal{"elephant"}monkey := Animal{"monkey"}m.Set("elephant", elephant)// Set:添加元素m.Set("monkey", monkey)tmp, ok := m.Get("elephant")// Get:獲取元素if ok ==false{log.Error("ok should be true for item stored within the map.")}elephant, ok = tmp.(Animal)// 類型斷言,轉成指定類型,key為指針時需要加*if!ok {log.Error("expecting an element, not null.")}if elephant.name !="elephant"{log.Error("item was modified.")}if m.Has("elephant")==false{// Has:是否有這個元素log.Error("element exists, expecting Has to return True.")}m.Remove("monkey")// Remove:去除元素if m.Count()!=0{log.Error("Expecting count to be zero once item was removed.")}monkey = Animal{"monkey"}m.Set("monkey", monkey)v, exists := m.Pop("monkey")// Pop:從map中獲取這個元素并刪除if!exists {log.Error("Pop didn't find a monkey.")}m1, ok := v.(Animal)if!ok || m1 != monkey {log.Error("Pop found something else, but monkey.")}if m.Count()!=100{// Count: 計算map中元素個數log.Error("Expecting 100 element within map.")}if m.IsEmpty()==false{// IsEmpty:判斷map是否為nillog.Error("new map should be empty")}// 插入100個元素for i :=0; i <100; i++{m.Set(strconv.Itoa(i), Animal{strconv.Itoa(i)})}counter :=0// Iterate over elements.for item :=range m.IterBuffered(){// IterBuffered:獲取緩沖迭代器,可用于for循環println(item.Val)val := item.Valname := item.Val.(Animal).namefmt.Println(name)if val ==nil{log.Error("Expecting an object.")}counter++}m.Clear()// Clear:清空map// Insert 100 elements.for i :=0; i <100; i++{m.Set(strconv.Itoa(i), Animal{strconv.Itoa(i)})}// Iterate over elements.m.IterCb(func(key string, v interface{}){// IterCb:遍歷map,獲取key,valuenum, ok := v.(Animal)fmt.Println(key,"---",num.name)if!ok {log.Error("Expecting an animal object")}counter++})items := m.Items()// Items:轉換成map[string]interface{}iflen(items)!=100{log.Error("We should have counted 100 elements.")}m.Clear()m.Set("a",1)m.Set("b",2)j, err := json.Marshal(m)// 轉換成json格式if err !=nil{log.Error(err)}fmt.Println(j)keys := m.Keys()// Keys:獲取map的key列表println(keys)animals :=map[string]interface{}{"elephant": Animal{"elephant"},"monkey": Animal{"monkey"},}m.MSet(animals)// MSet:同時添加多個元素println(m.Count())dolphin := Animal{"dolphin"}whale := Animal{"whale"}tiger := Animal{"tiger"}lion := Animal{"lion"}cb :=func(exists bool, valueInMap interface{}, newValue interface{})interface{}{nv := newValue.(Animal)if!exists {return[]Animal{nv}}res := valueInMap.([]Animal)returnappend(res, nv)}m.Set("marine",[]Animal{dolphin})m.Upsert("marine", whale, cb)// Upsert:插入或更新元素m.Upsert("predator", tiger, cb)m.Upsert("predator", lion, cb)}