-2

What is the difference in returning

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

or returning like

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

errorString is defined as follow

type errorString struct { text string }

error is defined as follow

type error interface {
  Error() string
}

I especially want to know what the difference in the return value is:

return &errorString{text}
      vs.
return errorString{text}

I already read the guide but it didn't mentioned the difference. It only mentioned, that with one you are not able to use equal what you do not want with the error object.

Charlie
  • 1,169
  • 2
  • 16
  • 31

1 Answers1

1

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"}
}
kingkupps
  • 3,284
  • 2
  • 16
  • 28