Search code examples
gomultiple-return-values

Multiple return value and := in go


Why is this a valid program?

package main

import "fmt"

func giveMeError(limit int) ([]string, error) {
    return nil, fmt.Errorf("MY ERROR %d", limit)
}

func main() {

    res1, err := giveMeError(1)
    if err == nil {
        fmt.Println("res", res1)
    } else {
        fmt.Println("err", err)
    }

    res2, err := giveMeError(5)
    if err == nil {
        fmt.Println("res", res2)
    } else {
        fmt.Println("err", err)
    }

}

And this isn't?

package main

import "fmt"

func giveMeError(limit int) ([]string, error) {
    return nil, fmt.Errorf("MY ERROR %d", limit)
}

func main() {

    res, err := giveMeError(1)
    if err == nil {
        fmt.Println("res", res)
    } else {
        fmt.Println("err", err)
    }

    res, err := giveMeError(5)
    if err == nil {
        fmt.Println("res", res)
    } else {
        fmt.Println("err", err)
    }

}

Complains that ./main.go:18: no new variables on left side of :=

I thought := cannot be used to change value to existing variables?


Solution

  • The documentation is clear at this point:

    In a := declaration a variable v may appear even if it has already been declared, provided:

    this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §), the corresponding value in the initialization is assignable to v, and there is at least one other variable in the declaration that is being declared anew.