英文:
How to change attribute value with pointer
问题
我正在尝试更改结构体中的一个值。不幸的是,""" ==>", flow" 中的值没有改变。我不明白为什么。
你能帮我解释一下为什么指针在切片中没有对应吗?也许我应该写一个指针的切片?
提前谢谢你。
package main
import (
"fmt"
)
type Foo struct {
value float64
}
var flows []Foo;
func AddFoo(foo Foo) {
flows = append(flows, foo)
}
func UpdateFoo(stream *Foo) {
stream.value = 5.00
}
func main() {
x := Foo{1.00}
AddFoo(x)
UpdateFoo(&x)
fmt.Println(x)
for _, flow := range flows {
fmt.Println(" ==>", flow)
}
}
英文:
I am trying to change a value within a struct. Unfortunately, the value in "" ==>", flow" doesn't change. I don't understand why.
Can you help me to explain why the pointer doesn't correspond in Slice. May be I must write a slice of pointer ?
Thank you in advance.
package main
import (
"fmt"
)
type Foo struct {
value float64
}
var flows []Foo;
func AddFoo(foo Foo) {
flows = append(flows, foo)
}
func UpdateFoo(stream *Foo) {
stream.value = 5.00
}
func main() {
x := Foo{1.00}
AddFoo(x)
UpdateFoo(&x)
fmt.Println(x)
for _, flow := range flows {
fmt.Println(" ==>", flow)
}
}
答案1
得分: 1
在你的函数AddFoo
中,你将Foo的副本添加到了切片中,然后在UpdateFoo
中,你修改了x
,但它并不是切片中的那个变量。
是的,如果你创建一个指针的切片,它会起作用。
英文:
In your function AddFoo
you are adding a copy of Foo to your slice, then in UpdateFoo
you are changing x
which is not the same variable as the one in the slice.
Yes, if you'd create a slice of pointers it'd work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论