Shadowed Identifiers Hide Outer Scope
Inner := declarations shadow outer identifiers inside their own scope; learn the patterns that silently hide values and how to avoid them.
Code
package main
import "fmt"
func main() {
user := "root"
{
user := "guest" // shadowed: 内层 := 新建同名变量,遮蔽外层
fmt.Println("inner:", user)
}
fmt.Println("outer:", user) // 外层不受影响
// if 短语句声明的变量只在 if 作用域可见
if n := 42; n > 10 {
fmt.Println("scoped n:", n)
}
// fmt.Println(n) // 编译错误:n 不在这个作用域
// 易错点:for 里想累加却误写 := 会创建新变量
total := 0
for _, n := range []int{1, 2, 3} {
total += n // 正确:+= 修改外层变量
}
fmt.Println("total:", total)
}What the code does
Shadowed Identifiers Hide Outer Scope is built around the function main.
Repetition is confined to for _, n := range []int{1, 2, 3} — the rest of the file is straight-line.
Applying it
The demo output is labeled (inner:, outer:, scoped n:), so each printed line points back to the operation that produced it.
Statements that matter
for _, n := range []int{1, 2, 3} {
total += n // 正确:+= 修改外层变量
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Shadowed Identifiers Hide Outer Scope print when run?
- No setup needed: run the file and look for labeled lines like `inner:`, `outer:`, `scoped n:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.