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>
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.
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).