Go Details & Tips 101 (20220829) by Tapir Liu

Go Details & Tips 101 (20220829) by Tapir Liu

Author:Tapir Liu
Language: eng
Format: epub


The famous := trap

Let's view a simple program.

package main import "fmt" import "strconv" func parseInt(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { b, err := strconv.ParseBool(s) if err != nil { return 0, err } if b { n = 1 } } return n, err } func main() { fmt.Println(parseInt("true")) }

We know that the call strconv.Atoi(s) will return a non-nil error, but the call strconv.ParseBool(s) will return a nil error. Then, will the call parseInt("true") return a nil error, too? The answer is it will return a non-nil error.

Wait, isn't the err variable is re-declared in the inner code block and its value has been modified to nil before the parseInt("true") returns? This is a confusion many new Go programmers, including me, ever encountered when they just started using Go.

The reason why the call parseInt("true") returns a non-nil error is a variable declared in an inner code block is never a re-declaration of a variable declared in an outer code block. Here, the inner declared err variable is set (initialized) as nil. It is not a re-declaration (a.k.a. modification) of the outer declared err variable. The outer one is set (initialized) as a non-nil value, then it is never changed later.

There is the voice to remove the ... := ... re-declaration syntax form from Go. But it looks this is a too big change for Go. Personally, I think explicitly marking the re-declared variables out is a more feasible solution.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.