Golang变量的遮蔽问题

huangapple go评论117阅读模式
英文:

Golang shadowing variable

问题

为什么在这段代码中变量'a'被遮蔽了?我在外部作用域中定义了它,然后在内部作用域中我必须使用':='语法为其赋予新值(来自函数调用的结果),因为我还需要一个新的变量'err'。但是这样会遮蔽'a',而且稍后在代码块外部,'a'会自动返回到初始值。

结果是:

  1. here: inside WTF?
  2. but here: outside

所以这迫使我在内部块中使用一个新变量,比如'b',然后将'b'赋值给'a',像这样?这样做很愚蠢,对吗?我觉得我在这里漏掉了什么。请帮忙解答。

  1. func work() {
  2. a := "outside"
  3. {
  4. b, err := foo()
  5. a = b // 我不想这样做!!!
  6. fmt.Printf("here: %v %v\n", a, err)
  7. }
  8. fmt.Printf("but here: %v \n", a)
  9. }
英文:

Why in this code the variable 'a' is shadowed? I define it in outer scope, then, in the inner scope I have to use the ':=' syntax to assign a new value to it (result from a function call), because I also need to have the 'err' variable, which is new. But this shadows 'a', and later, outside the block, the 'a' returns automatically to the initial value.

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func work() {
  6. a := "outside"
  7. {
  8. a, err := foo()
  9. fmt.Printf("here: %v %v\n", a, err)
  10. }
  11. fmt.Printf("but here: %v \n", a)
  12. }
  13. func foo() (string, error) {
  14. return "inside", fmt.Errorf("WTF?")
  15. }
  16. func main() {
  17. work()
  18. }

The result is:

  1. here: inside WTF?
  2. but here: outside

So this forces me to use a new variable in the inner block, e.g. 'b', and then assign 'b' to 'a', like this? This would be stupid, wouldn't it? I feel like I am missing something here. Please help.

  1. func work() {
  2. a := "outside"
  3. {
  4. b, err := foo()
  5. a = b // I DON'T WANT THIS !!!
  6. fmt.Printf("here: %v %v\n", a, err)
  7. }
  8. fmt.Printf("but here: %v \n", a)
  9. }

答案1

得分: 3

你正在使用短变量声明,这将重新声明外部作用域中的变量,从而遮蔽它们。你可以简单地声明错误变量,并使用常规赋值。

  1. func work() {
  2. a := "outside"
  3. {
  4. var err error
  5. a, err = foo() // 没有遮蔽
  6. }
  7. fmt.Printf("但是这里:%v \n", a)
  8. }
英文:

You are using short-form variable declaration, which will redeclare the variables in the outer scope, and thus, shadowing them. You can simply declare the error variable, and use regular assignment

  1. func work() {
  2. a := "outside"
  3. {
  4. var err error
  5. a, err = foo() // No shadowing
  6. }
  7. fmt.Printf("but here: %v \n", a)
  8. }
  9. </details>

huangapple
  • 本文由 发表于 2023年5月1日 04:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76143322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定