In https://blog.golang.org/error-handling-and-go, it shows the well-known 
error interface:

type error interface {
    Error() string
}

and it gives an example of a user-defined error:

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

I notice that it's returning a *pointer* to an error object.  My question 
is: is there a particular reason for returning a pointer here, rather than 
a direct instance of an error?

The word "pointer" doesn't appear anywhere in that blog posting.  Clearly a 
pointer allows the possibility of returning "nil" - but an interface 
variable can have a nil value <https://tour.golang.org/methods/13> too. 
Without the pointers, it becomes:

func (e errorString) Error() string {
    return e.s
}

func New(text string) error {
    return errorString{text}
}

and this appears to work the same - see a longer example on play 
<https://play.golang.org/p/joVzZ-PPs8E> (based on someone else's example, 
but I just removed the pointers).

I'm aware that the method set of *T includes the methods of T, so a pointer 
functions perfectly well in place of a concrete value to implement an 
interface.  Also, passing a pointer might be slightly more efficient, in 
that it reduces a bit of copying.  Other than that, is there a reason why 
code should return pointers to error objects rather than error objects?

I did try looking through the FAQ, which asks "Should I define methods on 
values or pointers? 
<https://golang.org/doc/faq#methods_on_values_or_pointers>" (although not 
"should I return values or pointers?"), and ends up by saying:


*For types such as basic types, slices, and small structs, a value receiver 
is very cheap so unless the semantics of the method requires a pointer, a 
value receiver is efficient and clear.*

Which makes me wonder if I'm missing some other reason for using pointers 
in this context.

Many thanks,

Brian.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/b7bed7ae-60f9-427f-b7a4-e317520a894f%40googlegroups.com.

Reply via email to