This question already has an answer here:
I'm struggling with go's receivers and pointers. I found that 4th pattern causes error. Why this pattern causes error and what's the difference? Thanks in advance.
type MyError struct{}
// OK pattern
func (e MyError) Error() string {
return "something bad happened"
}
func run() error {
return MyError{}
}
// OK pattern
func (e MyError) Error() string {
return "something bad happened"
}
func run() error {
return &MyError{}
}
// OK pattern
func (e *MyError) Error() string {
return "something bad happened"
}
func run() error {
return &MyError{}
}
// BAD pattern
func (e *MyError) Error() string {
return "something bad happened"
}
func run() error {
return MyError{}
}
</div>
Go will automatically dereference a pointer for you (pattern 2), however it won't automatically reference one for you. See https://golang.org/ref/spec#Method_values for more information.