douyousu9691 2017-05-02 03:45
浏览 15
已采纳

如何使用指针更改属性值

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条回答 默认 最新

  • dqmnueuu459279 2017-05-02 03:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥15 这怎么做,怎么在我的思路下改下我这写的不对
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
  • ¥20 如何用Python处理单元格内连续出现的重复词语?
  • ¥15 小程序有个导出到插件方式,我是在分包下引入的插件,这个export的路径对吗,我看官方文档上写的是相对路径
  • ¥20 希望有人能帮我完成这个设计( *ˊᵕˋ)
  • ¥100 将Intptr传入SetHdevmode()将Intptr传入后转换为DEVMODE的值与外部代码不一致
  • ¥50 基于ERA5数据计算VPD