Clashing global and local variable name

佐手、 提交于 2020-03-24 00:39:18

问题


Here is the code snippet in question:

package main

import (
    "fmt"
)

var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    a := "bye"

    fmt.Println(a, b)
}

Output:

hello world
bye world

My question is, how do I resolve name clash between the "global" and "local" variables a?

More specifically, how do I tell Go which a to use?


回答1:


I think your original example illustrates the situation well. Just like most in programming languages the scope matters.

The scoping closest to the use is what decides the value of a. So if you redeclare (:=) the variable inside your function, then for the duration of that function you will have the value "bye".

If you chose to use the same name for two things, the consequence is that the inner name will always dominate. If you need both values then name the variables differently.




回答2:


Well, this is not really a solution but a workaround. Before creating a shadowning variable, you can make a pointer to an outside variable.

var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    pa := &a
    a := "bye"

    fmt.Println(*pa, b, a)
}



回答3:


This is called variable shadowing. You just name them differently.

You can't just ask go to behave differently.



来源:https://stackoverflow.com/questions/47624326/clashing-global-and-local-variable-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!