上QQ阅读APP看书,第一时间看更新
Scope
The variables have a scope or visibility that is also connected to its lifetime. This can be one of the following:
- Package: The variable is visible in all the packages; if the variable is exported, it is also visible from other packages.
- Function: The variable is visible inside the function that declares it.
- Control: The variable is visible inside the block in which it's defined.
The visibility goes down, going from package to block. Since blocks can be nested, outer blocks don't have visibility over the variables of inner blocks.
Two variables in the same scope cannot have the same name, but a variable of an inner scope can reuse an identifier. When this happens, the outer variable is not visible in the inner scope – this is called shadowing, and it needs to be kept in mind in order to avoid issues that are hard to identify, such as the following:
// this exists in the outside block
var err error
// this exists only in this block, shadows the outer err
if err := errors.New("Doh!"); err !=
fmt.Println(err) // this not is changing the outer err
}
fmt.Println(err) // outer err has not been changed