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 is that not so?

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 that it is :=impossible to use for change of value for existing variables?

+4
source share
3 answers

The documentation is clear at this point:

The variable v may appear in the expression a: =, even if it has already been declared under the condition:

this declaration is in the same scope as the existing declaration v (if v is already declared in the outer scope, then the declaration will create a new variable ยง), the corresponding value in the initialization is assigned to v, and there is at least one other variable in the declaration that is declared again .

+8

, . , error .

, = . - , Go. , , .

+2

klashxx .

- .

package main

import "fmt"

func main(){
     a, b := 1, 2            
     fmt.Println(a, b)
     {
         b, c := 100, 200       //NOTE: b here is a new variable
         fmt.Println(a, b, c)
     }

     fmt.Println(a, b)

     b, c := 1000, 2000
     fmt.Println(a, b, c)
}
+2

Source: https://habr.com/ru/post/1649569/


All Articles