Why pointer receivers are everywhere

Particularly in this doc

func (e *QueryError) Unwrap() error { return e.Err }

As far as i understood pointer receiver should only be used when need to modify receiver value.
In example above it’s a plain return of receiver value field value.

Am i missing anything or it can (and should) be simplified down to

func (e QueryError) Unwrap() error { return e.Err }

?

Here is a good document to describe when to use ponter receivers

To be short, the document states " If in doubt, use a pointer,"

2 Likes

And when not in doubt.

E.g. in this case:

type QueryError struct {
    Query string
    Err   error
}

func (e *QueryError) Error() string { return e.Query + ": " + e.Err.Error() }

Clearly no need to point to QueryError since no mutation, right ?

(just trying to understand).

:slight_smile:
Then you can apply :
"If the receiver is a large struct or array, a pointer receiver is more efficient. How large is large? Assume it’s equivalent to passing all its elements as arguments to the method. If that feels too large, it’s also too large for the receiver. "

1 Like

Right, thank you :slight_smile:

Hi,

There’s a case where a pointer is absolutely mandatory and most people miss it. It’s when you can’t copy the state of the structure. Look at mutex for example. The documentation says you can’t copy one of them :

A Mutex must not be copied after first use.

Why ? Because, the mutex implies it gets all the concurrent calls to synchronize them according a referent state. If you copy the mutex and its state, you can’t synchronize anymore. To prevent this situation to occur, the methods Lock and Unlock have pointers receivers so that you can’t use them on a copy.

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