douxin5953 2018-04-14 16:15
浏览 105
已采纳

在Go的struct字段中为非原始类型使用指针更好吗

I am going on a project which process some data, I am wondering that if it is better to use pointer in non-primitive typed fields of struct.

What I've found is that the reason of using pointer is that nil can be used as a zero-value, is this the only reason to use pointer?

For example, I am going to store time.Time in my struct and it cannot be nil, then is it better to use non-pointer field?

So is it okay to use

type A struct {
   CreatedAt   time.Time
}

rather than

type A struct {
    CreatedAt   *time.Time
}

when Now is not going to be nil?

  • 写回答

2条回答 默认 最新

  • duanqian3953 2018-04-14 16:38
    关注

    I'm not really a professional or know the ins and outs of Go, so take everything I say with some grain of salt.

    But as I am understanding it, you should most likely use pointers.

    This is because every time you use a non-pointer type, the whole struct will be part of your struct in memory. As a consequence, you can't share a single instance of a struct between multiple structs - every single one gets a copy of your original struct.

    Heres a small example:

    // This struct has 2x64 bits in size
    type MyStruct struct {
        A uint64
        B uint64
    }
    
    // This struct has 32 + 2x64 bits in size
    type MyOtherStruct struct {
        C uint32
        Parent MyStruct
    }
    
    // This struct has 32 + the length of an address bits size 
    type MyPointerStruct struct {
        D uint32
        Parent *MyStruct
    }
    

    But apart from memory concerns, there is also a performance hit if your inner struct is very big. Because every time you set the inner struct the whole memory has to be copied to your instance.

    However you have to be careful if your are dealing with interfaces or structs. At runtime, an interface is represented as a type with two fields: A reference to the actual (runtime) type and one with a reference to the actual instance.

    So I - with my unprofessional opinion - would recommend to not use pointers if you have interface types because otherwise the CPU has to deference twice (once to get the interface reference, and then again to get the instance of the interface).

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

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示