sax
sax

Reputation: 73

Why do we return a pointer not a value in this example?

package main

import "fmt"


type argError struct {
    arg  int
    prob string
}

func (e *argError) Error() string {
    return fmt.Sprintf("%d - %s", e.arg, e.prob)
}

func f2(arg int) (int, error) {
    return -1, &argError{arg, "can't work with it"}
}

func main() {

    _, e := f2(42)
    if ae, ok := e.(*argError); ok {
        fmt.Println(ae.arg)
        fmt.Println(ae.prob)
    }
}

in f2 we have pointer &argError... as return value, but method declared to return error. Why f2 signature is not defined as

func f2(arg int) (int, *error) instead? Or why do we return pointer not a value in this case?

Upvotes: 0

Views: 149

Answers (1)

leaf bebop
leaf bebop

Reputation: 8212

error is an interface that asks to have an Error() string method.

The problem here is that you declare the Error() string method on a pointer. func (e *argError) Error() string, thus only an *argError implements an error, but not an argError. So you can only return an &argError{...}.

You should know that *error and error of an pointer is different. The former is a pointer to an interface holding whatever concrete type and the latter is an interface holding a pointer.

In practice, since an interface is all about methods, a pointer to an interface is rarely useful while an interface holding a pointer is widely used.

Upvotes: 4

Related Questions