为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
温温酱 2022-08-24 17:29:04
我知道地图可以像这样访问: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 datafunc 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
查看完整描述

1 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

你必须明确地说你想要这两个值


// Retrieves data

func Get(key string) (interface{}, bool) {

    mux.Lock()

    defer mux.Unlock()


    v ,ok := bag[key]

    return v, ok 

}


查看完整回答
反对 回复 2022-08-24
  • 1 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号