猿问

从函数返回时访问映射时强制返回 2 个值

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


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"

}

如何在从函数返回时从访问映射中强制返回这两个值?我使用 Go 1.15bagGet


温温酱
浏览 82回答 1
1回答

狐的传说

你必须明确地说你想要这两个值// Retrieves datafunc Get(key string) (interface{}, bool) {    mux.Lock()    defer mux.Unlock()    v ,ok := bag[key]    return v, ok }
随时随地看视频慕课网APP

相关分类

Go
我要回答