覆盖全局变量

时间:2019-10-02 10:21:34

标签: go

我想知道为什么下面的代码中没有警告或错误,因此我可以覆盖全局变量。

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

type MyStruct struct {
    MyInt uint32
}

func (s *MyStruct) MyMethod() {
    fmt.Println(s.MyInt)
}

var theStruct MyStruct

func main() {

    // Override the above global variable
    // I would expect some kind of warning or error here?
    theStruct := MyStruct {
        MyInt: 42,
    }

    // Outputs 42
    theStruct.MyMethod()

    // Outputs 0
    UseMyStruct()
}

func UseMyStruct() {
    theStruct.MyMethod()
}

1 个答案:

答案 0 :(得分:2)

允许变量隐藏父作用域中的其他变量。在您的示例中,作用域层次结构如下所示:

global (scope)
├── theStruct (variable)
└── main (scope)
    └── theStruct (variable)

通常使用err完成这样的阴影操作:

package main

import (
    "io/ioutil"
    "log"
)

func main() {
    f, err := ioutil.TempFile("", "")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    // This err shadows the one above, it is technically in its
    // own scope within the "if".
    if _, err := f.Write([]byte("hello world\n")); err != nil {
        log.Fatal(err)
    }

    if true {
        // We can even shadow with different types!
        err := 3

        log.Println(err)
    }
}

此示例部分来自“ Scope and Shadowing in Go”。