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

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

WBOY
Release: 2024-02-05 23:57:11
forward
456 people have browsed it

为什么 `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
Copy after login

Case 2:

str, err := m.something(); 

fmt.println(str)  //str is ok
Copy after login

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
    }
Copy after login


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
// ...
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template