gpt4 book ai didi

dictionary - 从 map 返回传递

转载 作者:IT王子 更新时间:2023-10-29 02:09:55 30 4
gpt4 key购买 nike

我为围棋的Web Crawler练习写了如下类型和Get函数。

type UrlCache struct {
urls map[string]string
mux sync.Mutex
}

func (c *UrlCache) Get(key string) (value string, ok bool) {
c.mux.Lock()
defer c.mux.Unlock()
value, ok = c.urls[key]
return
}

一切正常,但我想知道是否有改进 Get 函数的方法,我尝试了以下方法:

func (c *UrlCache) Get(key string) (string, bool) {
c.mux.Lock()
defer c.mux.Unlock()
return c.urls[key]
}

但是那会抛出

prog.go:24:2: not enough arguments to return
have (string)
want (string, bool)

有没有办法将 get 的两个返回值都作为返回值传递到 map 上?

最佳答案

在单个 return 语句中是不可能的。

原因在于 Spec: Index expressions:

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

强调的是,特殊的逗号-ok 形式只能用于赋值或初始化。您尝试在 return 语句中使用它,因此索引表达式只产生一个结果,因此会出现编译时错误。

而且由于 Go 中的赋值不是表达式而是语句,你甚至不能做这样的事情:

return (value, ok = c.urls[key]) // COMPILE-TIME ERROR!

关于dictionary - 从 map 返回传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921496/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com