戈朗地图放如果缺席?

我有一个格式的地图:

map[string]map[string]int

在这个主地图中,我想做一些像我们在Java中一样的事情。在 Go 中,什么是干净且速记的方法?putIfAbsent("key", new HashMap<>()


四季花海
浏览 68回答 3
3回答

红糖糍粑

您可以执行以下操作:var val map[string]intval, exists := m[key]if !exists {&nbsp; &nbsp; val = make(map[string]int)&nbsp; &nbsp; m[key] = val}如果您不需要下面的代码:valif _,exists := m[key]; !exists {&nbsp; &nbsp; m[key]=make(map[string]int)}

一只斗牛犬

如果您不打算立即使用该值,那么在这里...m := make(map[string]map[string]int)if _, ok := m["unknown"]; !ok {&nbsp; &nbsp; m["unknown"] = make(map[string]int)}以下是改进建议:为了保持整洁易懂,您可以定义自己的类型。例如,如果您的数据是“城市到老年人”的映射,我会这样做:type Person map[string]inttype City map[string]Personm := make(City)if _, ok := m["Dhaka"]; !ok {&nbsp; &nbsp; m["Dhaka"] = make(Person)}

守着星空守着你

func main() {&nbsp; &nbsp; var testMap map[int]interface{}&nbsp; &nbsp; testMap = make(map[int]interface{})&nbsp; &nbsp; var addMap map[int]string&nbsp; &nbsp; addMap = make(map[int]string)&nbsp; &nbsp; addMap[1] = "999"&nbsp; &nbsp; addMap[2] = "888"&nbsp; &nbsp; Add(testMap, 111, addMap)&nbsp; &nbsp; for key, val := range testMap {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(key)&nbsp; &nbsp; &nbsp; &nbsp; for key2, val2 := range val.(map[int]string) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(key2, val2)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func Add(_testMap map[int]interface{}, _key int, _val map[int]string) {&nbsp; &nbsp; _, exist := _testMap[_key] // _ -> value&nbsp; &nbsp; if exist == false {&nbsp; &nbsp; &nbsp; &nbsp; //addmap&nbsp; &nbsp; &nbsp; &nbsp; _testMap[_key] = _val&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //whatever wanna to do&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go