errorString{text}
is a struct and &errorString{text}
is a pointer to a struct. See https://tour.golang.org/moretypes/1 for a more detailed explanation of what this means.
There is also this question which has specifics on when to return which: Pointers vs. values in parameters and return values. Returning errorText{text}
returns a copy of the entire struct while &errorText{text}
returns a pointer to a struct instead.
A struct S
and a pointer to a struct of type S
are two separate types in Go. For errorText
to implement the error
interface, errorText
must implement the Error() string
method but it also needs to have the correct receiver type.
For example, this is OK:
type errorText struct {
text string
}
func (e errorText) Error() string { return e.text }
func SomethingThatReturnsYourError() error {
return errorText{"an error"}
}
This is also OK:
type errorText struct {
text string
}
func (e errorText) Error() string { return e.text }
func SomethingThatReturnsYourError() error {
return &errorText{"an error"} // Notice the &
}
But this is not OK and the compiler will hit you with an error:
type errorText struct {
text string
}
// notice the pointer receiver type
func (e *errorText) Error() string { return e.text }
func SomethingThatReturnsYourError() error {
return errorText{"an error"}
}
Error message: cannot use errorString literal (type errorString) as type error in return argument:
errorString does not implement error (Error method has pointer receiver)
In order to use a pointer receiver you have to return a pointer:
type errorText struct {
text string
}
func (e *errorText) Error() string { return e.text }
func SomethingThatReturnsYourError() error {
return &errorText{"an error"}
}