Golang变量的遮蔽问题

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

Golang shadowing variable

问题

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

结果是:

here: inside WTF?
but here: outside

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

func work() {
    a := "outside"

    {
        b, err := foo()
        a = b // 我不想这样做!!!
        fmt.Printf("here: %v %v\n", a, err)
    }

    fmt.Printf("but here: %v \n", a)
}
英文:

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.

package main

import (
	"fmt"
)

func work() {
	a := "outside"

	{
		a, err := foo()
		fmt.Printf("here: %v %v\n", a, err)
	}

	fmt.Printf("but here: %v \n", a)
}

func foo() (string, error) {
	return "inside", fmt.Errorf("WTF?")
}

func main() {
	work()
}

The result is:

here: inside WTF?
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.

func work() {
    a := "outside"

    {
        b, err := foo()
        a = b // I DON'T WANT THIS !!!
        fmt.Printf("here: %v %v\n", a, err)
    }

    fmt.Printf("but here: %v \n", a)
}

答案1

得分: 3

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

func work() {
    a := "outside"

    {
        var err error
        a, err = foo() // 没有遮蔽
    }

    fmt.Printf("但是这里:%v \n", a)
}
英文:

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

func work() {
    a := "outside"

    {
        var err error
        a, err = foo() // No shadowing
    }

    fmt.Printf("but here: %v \n", a)
}

</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:

确定