This is a creation in Article, where the information may have evolved or changed.
This post was about declaration scopes and shadowing in Go.
Package Mainimport "FMT" Func f (x intx: = 0; x < ten; PRINTLN (x)}}var x intfunc main () {var x =$ f (x)}
This program declares the four times x . All four is different variables because they exist in different scopes.
Package Mainimport "FMT" Func f () {x: = $FMT. Println ("Inside f:x =", x)}func main () {x: =. Fmt. Println ("Inside main:x =", x) F () fmt. Println ("Inside main:x =", x)}
In Go the scope of a declaration are bound to the closest pair of curly braces, { and } . In this example, we declare to be x inside main, and inside f .
What does expect this program would print?
Package Mainimport "FMT" Func Main () {x: =+ for I: = 0; i < 5; i++ {x: = ifmt. PRINTLN (x)}fmt. PRINTLN (x)}
There is several scopes in a Go program; Block scope, function scope, file scope, package scope, and universe scope. Each scope encompasses the previous. What's seeing is called shadowing.
var x =the func main () { var x =$ fmt. PRINTLN (x)}
Most developers is comfortable with a function scoped variable shadowing a package scoped variable.
Func f () { var x = if x > + x: = . Fmt. PRINTLN (x) }}
But a block scoped variable shadowing a function scoped variable may be surprising.
The justification for a declaration in one scope shadowing another is consistency, prohibiting just block scoped Declarati ONS from shadowing another scopes, would be inconsistent.
Related Posts:
- Stupid Go Declaration Tricks
- Associative commentary
- Channel axioms
- What's the zero value, and why is it useful?