如何使用指针更改属性值

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

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.

huangapple
  • 本文由 发表于 2017年5月2日 19:45:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/43737030.html
匿名

发表评论

匿名网友

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

确定