drtohng5613 2015-08-25 15:41
浏览 69
已采纳

Go构造函数中返回值vs指针

When building a simple object in go, what's the difference between these alternatives?

func NewGender(value string) Gender {
    return Gender{strings.TrimSpace(value)}
}

func NewGender(value string) *Gender {
    return &Gender{strings.TrimSpace(value)}
}
  • 写回答

2条回答 默认 最新

  • doushouj966020 2015-08-25 16:13
    关注

    The question is a really broad one, and it depends heavily on the rest of your API. So here are just some things you might need to consider when choosing one over another (in no particular order):

    • Unnecessary pointers lead to more work for the GC. You might win some time by returning a pointer (one word) rather than a struct (zero to many words), but some of that time might later be consumed by the GC scan.

    • Pointers can also signal presence or absence of a thing, although it's generally better to use comma-ok idiom for that, or return an error.

    • Speaking of errors, if you return nil with an error, the chance that the error will be ignored is smaller (because nil pointer dereference will result in panic). Then again, I don't think people who ignore errors are something you should really take into account.

    • If you need some form of tracking (for example, a possibility to inspect all instances ever created by your constructor), you have to return a pointer, so that all changes to the value would be visible to the inspector.

    • If most of the type's methods have a pointer receiver, or most functions in the API accept pointers to the type rather than values, it's more ergonomic to return a pointer.

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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画