Scope of the lost variable

Would this be considered a bug on the part of the language?

This is an example to see the scope of a variable.

package main

import (
“fmt”
“errors”
)

func main() {
err := getError(1)
if err != nil {
mje, err := getFoo(2)
fmt.Printf(“m: %s err: %v \n”, mje, err)
}
fmt.Println(“Error:”, err)
}

func getError(n int) error {
return errors.New(fmt.Sprintf(“error %d”, n))
}

func getFoo(n int) (string, error) {
return “-”, errors.New(fmt.Sprintf(“error %d”, n))
}

The variable “err” should update the error, since it was declared before, or am I wrong?

https://play.golang.org/p/QuAf2HY7YZb

It’s not a bug in the language. := is not assignment. It’s a declaration and initialization of a variable. The err variable declared on line 11 is a separate variable whose namr “shadows” the err declared on line 9, but only within that scope. That inner err is no longer accessible after the closing }.

Thanks for answering @skillian

In other words, if I wanted to reuse the variable “err” inside the if I couldn’t do it?

Do I have to declare the variable “mje” outside the if and use “=” for the assignment?

Is there any other way?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.