-1

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{}
}
1
  • 4
    That's because non-pointer types do not include methods of pointer types in their method set: golang.org/ref/spec#Method_sets Commented Dec 18, 2018 at 9:58

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It will automatically reference one for you, if it can, but only for a method call, not for the purpose of satisfying an interface.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.