登录
首页 >  Golang >  Go问答

修改全局变量

来源:stackoverflow

时间:2024-03-04 08:12:21 379浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《修改全局变量》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我想知道为什么以下代码中没有警告或错误,允许我覆盖全局变量。

// 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()
}

解决方案


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

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”。

今天关于《修改全局变量》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>