Home > Software engineering >  Why does `if` change the scope of this variable
Why does `if` change the scope of this variable

Time:12-04

If I have something like this

Case 1:

if str, err := m.something(); err != nil {
        return err
    }

fmt.Println(str)  //str is undefined variable

Case 2:

str, err := m.something(); 

fmt.Println(str)  //str is ok

My question is why does the scope of the variable str change when its used in a format like this

 if str, err := m.something(); err != nil {
        return err
        //str scope ends
    }

CodePudding user response:

Because if statements (and for, and switch) are implicit blocks, according to the language spec, and := is for both declaration and assignment. If you want str to be available after the if, you could declare the variables first, and then assign to them in the if statement:

var s string
var err error

if str, err = m.something(); err != nil
// ...
  •  Tags:  
  • go
  • Related