golang return multiple values issue

后端 未结 5 1037
陌清茗
陌清茗 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: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.

提交回复
热议问题