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

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>

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.

Returning a pointer can be useful for a couple reasons.

  1. A pointer always has a fixed size. For larger structs, it's more efficient to just return a pointer rather than copy the struct's memory.
  2. Creating a new instance might fail. In this case your function could return a pointer and an error, where the pointer is nil if something went wrong.

In most cases it doesn't really matter if you return a pointer or not. I typically return a pointer for New unless the struct is extremely small. The compiler will protect you from accidentally passing around the wrong type.

Something more important to worry about is whether the methods for MyType accept a pointer or a value. If you want to be able to mutate the instance without affecting it outside the scope of the function, you need to pass it by value so you are working with a copy (keeping in mind that it is only a shallow copy).