dongnai2804 2019-07-27 16:12
浏览 47

在NewX函数上返回指针背后有充分的理由吗? [重复]

This question already has an answer here:

Is there a good reason for returning pointers on the "constructor" of a struct? For example:

type MyType struct{}

func NewMyType() *MyType {
  var m *MyType
  return m
}

vs.

type MyType struct{}

func NewMyType() MyType {
  var m MyType
  return m
}

In most cases, the "constructors" accept some arguments and return a pointer to a type. Why not just return a value?

Thanks in advance.

</div>
  • 写回答

2条回答 默认 最新

  • duandunzhuo3234 2019-07-27 17:50
    关注

    The return type typically depends on how the type is intended to be used. Here are some examples:

    The time.Time and reflect.Value types are intended to be used as values. The methods on these types have a value receiver. The constructor functions for these types return a value.

    The bufio.Reader type is passed around as a pointer. The type wouldn't work at all if bufio.Reader types are passed around as a value. The constructor functions return a pointer.

    All this begs the question about using values vs. pointers. That issue is covered well in other answers here on the StackOverflow.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!