Home >Backend Development >Golang >Why does `if` change the scope of this variable?

Why does `if` change the scope of this variable?

WBOY
WBOYforward
2024-02-05 23:57:11447browse

为什么 `if` 改变了这个变量的范围

Question content

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
    }

Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete