在从函数返回的过程中访问映射时,强制返回这两个值



我知道可以访问这样的地图:

value := someMap["someKey"]

要检查地图中是否存在密钥,我可以使用以下方法:

value, exists := someMap["someKey"]
if exists {
fmt.Printf("has value: %s", value)
}

然而,关于第二个代码,它在这种情况下不起作用:

var bag = make(map[string]interface{}, 0)
var mux = sync.Mutex{}
// Retrieves data
func Get(key string) (interface{}, bool) {
mux.Lock()
defer mux.Unlock()
return bag[key] // I receive "wrong number of return values (want 2, got 1)compiler"
}

在从Get函数返回的同时,如何强制返回访问bag映射的两个值?我使用Go 1.15

您必须明确表示您想要两个值

// Retrieves data
func Get(key string) (interface{}, bool) {
mux.Lock()
defer mux.Unlock()
v ,ok := bag[key]
return v, ok 
}

最新更新