donglinyi4313 2015-03-28 08:06
浏览 43
已采纳

去:结构体中的数组失去了它的内容

The following go code (shared: link) should insert two positions in an order (both order and position are structs:

package main

import "fmt"

type orderPosition struct{
   art string
   qty string   
}

type order struct{
   posList []orderPosition
}

func main() {
  o := new(order)
  o.loadPos()
  fmt.Printf("# pos: %d
",len(o.posList))

}

func (o order) loadPos() {
  o.posList = append(o.posList, orderPosition {art: "art 1", qty: "2 pc"})
  o.posList = append(o.posList, orderPosition {art: "art 2", qty: "7 pc"})
  fmt.Printf("# pos: %d
",len(o.posList))
}

The output is:

# pos: 2
# pos: 0    

The method loadPos fills the positions in the order. But as soon as the method is left the list of positions is lost.

Why is the array loosing its content?

Any help would be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • duanqu9279 2015-03-28 08:13
    关注

    Your loadPos() method is using a value receiver (as opposed to a pointer), meaning that it's operating on a copy of the order object.
    So when you call o.loadPos(), go is copying o, and calling loadPos() on that copy.

    The solution is to simply change the receiver to a pointer:

    func (o *order) loadPos() {
    

    https://play.golang.org/p/PATpBCZLT7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数