I have written the following type and Get function for the Web Crawler exercise of the go tour.
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
}
Everything works but I wonder if there is a way to improve the Get function, I have tried the following:
func (c *UrlCache) Get(key string) (string, bool) {
c.mux.Lock()
defer c.mux.Unlock()
return c.urls[key]
}
But that throws
prog.go:24:2: not enough arguments to return
have (string)
want (string, bool)
Is there a way to pass both return values of the get on the map as return?
It is not possible in a single return statement.
And the reason for this is in the Spec: Index expressions:
An index expression on a map a of type
map[K]Vused in an assignment or initialization of the special formv, 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
okistrueif the keyxis present in the map, andfalseotherwise.
The stress is that the special comma-ok form may only be used in an assignment or initialization. You try to use it in a return statement, so the index expression yields only a single result, hence the compile-time error you get.
And since assignments in Go are not expressions but statements, you can't even do something like:
return (value, ok = c.urls[key]) // COMPILE-TIME ERROR!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With