更新全局变量的成员在全局变量中没有反映出来。

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

update to global variable's member not reflecting in global variable

问题

首先,我是新手Go语言,所以我猜我正在尝试实现的方法可能是显而易见的。我遇到的问题是,当我运行test()时,以下代码不会打印"blah"。相反,它打印出一个nil,即使main()先执行。为什么全局变量的成员属性的更新在不同的函数中不会反映在自身上?

var GlobalMe SomeType

func main() {
    for _, member := range GlobalMe.Members {
        member.SomeProperty = "blah"
    }
    test()
}

func test() {
    for _, member := range GlobalMe.Members {
        fmt.Println("value:", member.SomeProperty)
    }
}
英文:

First of all, I am new to Go, so I guess it is obvious to me there is some proper way of doing what I am trying to achieve here.

The issue I am having is that the following code will not print "blah" when I run test(). Instead if prints a nil, even if main() was executed first. How come updating of a Global variable's member property does not get reflected on itself at a different function ?

var GlobalMe SomeType

func main() {
	for _,member := range GlobalMe.Members {
        member.SomeProperty = "blah"
    }
    test()
}

func test() {
	for _,member := range GlobalMe.Members {
        fmt.Println("value:", member.SomeProperty)
    }
}

答案1

得分: 1

如果你有:

type SomeMemberType struct {
  SomeProperty string
}

type SomeType struct {
  Members []SomeMemberType
}

var GlobalMe SomeType

只需将 SomeType 改为:

type SomeType struct {
  Members []*SomeMemberType
}

人们通常会觉得这很不直观,但当你处理更基本的类型时,这通常是有道理的:

xs := []int{1,2,3}
for _, x := range xs {
  x = 4
}
// xs 仍然是 {1,2,3}

实际上,这段代码无法编译通过,但如果可以的话,xs 不会改变。如果你想修改原始值,你需要这样做:

xs := []int{1,2,3}
for i := range xs {
  xs[i] = 4
}
// xs 现在是 {4,4,4}

这种行为在大多数编程语言中都很常见。Go 语言只是更加明确地通过对结构体采取相同的方式来处理。所以如果你想要类似 Java 的行为,可以使用指针。

英文:

If you have:

type SomeMemberType struct {
  SomeProperty string
}

type SomeType struct {
  Members []SomeMemberType
}

var GlobalMe SomeType

Simply change SomeType to:

type SomeType struct {
  Members []*SomeMemberType
}

People often find this unintuitive, but it usually makes sense when you deal
with more basic types:

xs := []int{1,2,3}
for _, x := range xs {
  x = 4
}
// xs is still {1,2,3}

This actually doesn't compile, but if it did xs wouldn't change. If you wanted
to modify the original you'd have to do:

xs := []int{1,2,3}
for i := range xs {
  xs[i] = 4
}
// xs is now {4,4,4}

This behavior is common in most programming languages. Go is just a little more explicit about it by doing the same thing for structs. (So if you want java-like behavior use pointers)

huangapple
  • 本文由 发表于 2015年8月17日 23:24:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/32054113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定