Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The reason for the emergence of shadowed err during compilation of go language

Shulou Source: shulou.com Published: 2022-06-02 04:51:15 09月26日 Update

This article focuses on "the reasons for the emergence of shadowed err in go language compilation", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the reason why shadowed err appears when go language compiles".

As a novice to golang, I often encounter a compilation error:

Err is shadowed during return

For example, the following code:

Func fun () (err error) {if true {x, err: = makeErr () if err! = nil {return} fmt.Println (x, err.Error ())} return} func makeErr () (x int Err error) {err = fmt.Errorf ("error") return}

Because the err initialized by the inner layer is not the return value of the fun function. On return, the inner err is ignored.

If you remove the if statement, the compilation error will disappear.

Func fun () (err error) {x, err: = makeErr () if err! = nil {return} return}

Of course, the logic of the code also changes. Typically, the way to handle this is to create a new err variable and then assign it:

Func fun () (err error) {if true {x, err1: = makeErr () if err1! = nil {err = err1 return} fmt.Println (x, err1.Error ())} return}

But personally, I think this way of writing is ugly. Looking at the go source code, you can find that the common practice in the source code is:

Func fun () error {var err error if true {x, err: = makeErr () if err! = nil {return err} fmt.Println (x, err.Error ())} return err} so far I believe that you have a deeper understanding of the "reasons for the emergence of shadowed err when compiling in the go language", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Compile reason language timeout code content inner layer method source code learning practical deeper ugly in this case individual practice interest writing function variable Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL OPPO Reno Docker Shulou Technology Huawei