douzongluo7542 2017-12-31 00:39
浏览 21
已采纳

关于如何在结构中保留Golang指针的困惑

I'm currently learning golang (mostly a Java/C# developer) and I hit an issue with pointers and defer.

I'm trying to wrap the writes to a CSV file under a struct in a OO-like style. From the examples I found online, it seems that creating "methods" on a struct could be done like so:

type MyObject struct {
    fp  *os.File
    csv *csv.Writer
}

func (mo MyObject) Open(filepath string) {

    println(&mo)
    var err error
    mo.fp, err = os.Create(filepath)
    if err != nil {
        panic(err)
    }

    mo.csv = csv.NewWriter(mo.fp)
}

The problem I hit was once I left the Open method, the pointers for fp and csv went back to null. Subsequent calls to this class would throw a nil error. A full example can be found here.

After a lot of googling, I ended up looking at how golang implemented their logger. They used a pointer to the object like so:

type MyObject struct {
    fp  *os.File
    csv *csv.Writer
}

func New() *MyObject {
    return &MyObject{}
}

func (mo *MyObject) Open(filepath string) {

    println(&mo)
    var err error
    mo.fp, err = os.Create(filepath)
    if err != nil {
        panic(err)
    }

    mo.csv = csv.NewWriter(mo.fp)
}

A refactoring of my code (see here) shows it works as expected. I'm still confused though why the first method didn't work. I'm guessing I'm misunderstanding something on how structs, pointers, and/or defer work. What am I missing?

  • 写回答

1条回答 默认 最新

  • doubeizhong5178 2017-12-31 01:11
    关注

    It didn't work in the first case, because func (mo MyObject) Open(filepath string) only got a local copy of MyObject...and all changes made to it remained within that context.

    But after you added * to the receiver, i.e (mo *MyObject) the changes within the function affected the original MyObject.

    you can check here for more info

    hope this helps

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

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示