修改全局变量
时间:2024-03-04
浏览: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学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
