Home > Article > Backend Development > Why does `if` change the scope of this variable?
If I have such a thing
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 used in this format
if str, err := m.something(); err != nil { return err //str scope ends }
Because the if
statement (and for
and switch
) isImplicit blocks, according to the language specification, :=
is used for declarations and assignments. If you want str
to be available after if
, you can declare the variable first and then assign it a value in the if statement:
var s string var err error if str, err = m.something(); err != nil // ...
The above is the detailed content of Why does `if` change the scope of this variable?. For more information, please follow other related articles on the PHP Chinese website!