Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing on return from a map get

Tags:

dictionary

go

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?

like image 507
crunsher Avatar asked Jan 17 '26 19:01

crunsher


1 Answers

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!
like image 133
icza Avatar answered Jan 19 '26 20:01

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!