从地图传递收益

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]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.

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!

My apologies, misread things:

When you return the map value, you are accessing the map in a 'single-value' context. You can access the map with one value returned, or with two. Unless you signal go that you want two values, you will only get one. So you can't really (if you do want to return two things) avoid getting the map value with the value, ok := signature. The first version of the function names the return parameters, allowing for a bare return statement at the end to 'just work', the second version would require

value, ok := c.urls[key]
return value, ok