Hello everybody Newbie question: When to return a pointer?

I understand the recommendations around using pointers vs. values as method receivers , but what about return values? If the returned type doesn’t need to satisfy another interface (i.e. it’s a plain struct that just contains some data), is it better to return the value or a pointer? It seems somewhat arbitrary, as the caller can just reference/dereference as needed.

A colleague made the following suggestion:

Let’s say you try to create a post via CreatePost but an error occurs. It returns the error and an empty Post object. One could conceive a world in which the error was not checked, the code goes about its business assuming the Post object is valid, and the programmer is spending their time trying to figure out what’s up further down the control flow. It gets worse if you have fields that are pointers.

This is internal code and we make sure to always handle errors, so this wasn’t very convincing to me.

The particular use-case is reading a User from the database:
GetUser(userID string) (api.User, error) vs. GetUser(userID string) (*api.User, error)

I did notice that constructors tend to return pointers.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.