golang return multiple values issue

后端 未结 5 1033
陌清茗
陌清茗 2021-02-05 08:47

I was wondering why this is valid go code:

func FindUserInfo(id string) (Info, bool) {
    it, present := all[id]
    return it, present
}

but

相关标签:
5条回答
  • 2021-02-05 09:37

    By default, maps in golang return a single value when accessing a key

    https://blog.golang.org/go-maps-in-action

    Hence, return all[id] won't compile for a function that expects 2 return values.

    0 讨论(0)
  • 2021-02-05 09:43

    Simply put: the reason why your second example isn't valid Go code is because the language specification says so. ;)

    Indexing a map only yields a secondary value in an assignment to two variables. Return statement is not an assignment.

    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]

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

    Furthermore, indexing a map is not a "single call to a multi-valued function", which is one of the three ways to return values from a function (the second one, the other two not being relevant here):

    There are three ways to return values from a function with a result type:

    1. The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.

    2. The expression list in the "return" statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a "return" statement listing these variables, at which point the rules of the previous case apply.

    3. The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.

    As for your actual question: the only way to avoid temporary variables would be using non-temporary variables, but usually that would be quite unwise - and probably not much of an optimization even when safe.

    So, why doesn't the language specification allow this kind of special use of map indexing (or type assertion or channel receive, both of which can also utilize the "comma ok" idiom) in return statements? That's a good question. My guess: to keep the language specification simple.

    0 讨论(0)
  • 2021-02-05 09:47

    To elaborate on my comment, the Effective Go mentions that the multi-value assignment from accessing a map key is called the "comma ok" pattern.

    Sometimes you need to distinguish a missing entry from a zero value. Is there an entry for "UTC" or is that the empty string because it's not in the map at all? You can discriminate with a form of multiple assignment.

    var seconds int
    var ok bool
    seconds, ok = timeZone[tz]
    

    For obvious reasons this is called the “comma ok” idiom. In this example, if tz is present, seconds will be set appropriately and ok will be true; if not, seconds will be set to zero and ok will be false.

    Playground demonstrating this

    We can see that this differs from calling a regular function where the compiler would tell you that something is wrong:

    package main
    
    import "fmt"
    
    func multiValueReturn() (int, int) {
        return 0, 0
    }
    
    func main() {
        fmt.Println(multiValueReturn)
    
        asgn1, _ := multiValueReturn()
    
        asgn2 := multiValueReturn()
    }
    

    On the playground this will output

    # command-line-arguments
    /tmp/sandbox592492597/main.go:14: multiple-value multiValueReturn() in single-value context
    

    This gives us a hint that it may be something the compiler is doing. Searching the source code for "commaOk" gives us a few places to look, including types.unpack

    At the time of writing this it this the method's godoc reads:

    // unpack takes a getter get and a number of operands n. If n == 1, unpack
    // calls the incoming getter for the first operand. If that operand is
    // invalid, unpack returns (nil, 0, false). Otherwise, if that operand is a
    // function call, or a comma-ok expression and allowCommaOk is set, the result
    // is a new getter and operand count providing access to the function results,
    // or comma-ok values, respectively. The third result value reports if it
    // is indeed the comma-ok case. In all other cases, the incoming getter and
    // operand count are returned unchanged, and the third result value is false.
    //
    // In other words, if there's exactly one operand that - after type-checking
    // by calling get - stands for multiple operands, the resulting getter provides
    // access to those operands instead.
    //
    // If the returned getter is called at most once for a given operand index i
    // (including i == 0), that operand is guaranteed to cause only one call of
    // the incoming getter with that i.
    //
    

    The key bits of this being that this method appears to determine whether or not something is actually a "comma ok" case.

    Digging into that method tells us that it will check to see if the mode of the operands is indexing a map or if the mode is set to commaok (where this is defined does give us many hints on when it's used, but searching the source for assignments to commaok we can see it's used when getting a value from a channel and type assertions). Remember the bolded bit for later!

    if x0.mode == mapindex || x0.mode == commaok {
        // comma-ok value
        if allowCommaOk {
            a := [2]Type{x0.typ, Typ[UntypedBool]}
            return func(x *operand, i int) {
                x.mode = value
                x.expr = x0.expr
                x.typ = a[i]
            }, 2, true
        }
        x0.mode = value
    }
    

    allowCommaOk is a parameter to the function. Checking out where unpack is called in that file we can see that all callers pass false as an argument. Searching the rest of the repository leads us to assignments.go in the Checker.initVars() method.

    l := len(lhs)
    get, r, commaOk := unpack(func(x *operand, i int) { check.expr(x, rhs[i]) }, len(rhs), l == 2 && !returnPos.IsValid())
    

    Since it seems that we can only use the "comma ok" pattern to get two return values when doing a multi-value assignment this seems like the right place to look! In the above code the length of the left hand side is checked, and when unpack is called the allowCommaOk parameter is the result of l == 2 && !returnPos.IsValid(). The !returnPos.IsValid() is somewhat confusing here as that would mean that the position has no file or line information associated with it, but we'll just ignore that.

    Further down in that method we've got:

    var x operand
    if commaOk {
        var a [2]Type
        for i := range a {
            get(&x, i)
            a[i] = check.initVar(lhs[i], &x, returnPos.IsValid())
        }
        check.recordCommaOkTypes(rhs[0], a)
        return
    }
    

    So what does all of this tell us?

    • Since the unpack method takes an allowCommaOk parameter that's hardcoded to false everywhere except in assignment.go's Checker.initVars() method, we can probably assume that you will only ever get two values when doing an assignment and have two variables on the left-hand side.
    • The unpack method will determine whether or not you actually do get an ok value in return by checking if you are indexing a slice, grabbing a value from a channel, or doing a type assertion
    • Since you can only get the ok value when doing an assignment it looks like in your specific case you will always need to use variables
    0 讨论(0)
  • 2021-02-05 09:47

    You may save a couple of key strokes by using named returns:

    func FindUserInfo(id string) (i Info, ok bool) {
        i, ok = all[id]
        return
    }
    

    But apart from that, I don't think what you want is possible.

    0 讨论(0)
  • 2021-02-05 09:53

    I'm no Go expert but I believe you are getting compile time error when you are trying to return the array i.e. return all[id]. The reason could be because the functions return type is specially mentioned as (Info, bool) and when you are doing return all[id] it can't map the return type of all[id] to (Info, bool).

    However the solution mentioned above, the variables being returned i and ok are the same that are mentioned in the return type of the function (i Info, ok bool) and hence the compiler knows what it's returning as opposed to just doing (i Info, ok bool).

    0 讨论(0)
提交回复
热议问题