How e assign to return value of method Error() but not address of argError?

Considering the example https://gobyexample.com/errors which its code in Go playground. When executing the segment of code:

for _, i := range []int{7, 42} {
    if r, e := f2(i); e != nil {
        fmt.Println("f2 failed:", e)
    } else {
        fmt.Println("f2 worked:", r)
    }
}

in the case i = 42, by definition of function f2, the second return value of f2(42) is a address of an object of argError type, but why e (in the line if r, e := f2(i); e != nil) is assigned to the return value of method Error() of type argError.

I guess the reason relates to the following sentence in the example

By convention, errors are the last return value and have type error , a built-in interface.

and the fact that type argError implement the Error() method of Error interface. But I need more details to figure out how the code work.

Your question is not clear. What exactly do you expect to happen where in this code? What does happen instead?

check my edited question

Even after you have edited your question, it is not more clear than before.

Could you please answer @lutzhorn’s quetsions:

I edited my question. Sorry for the late editing (my account was temporarily on hold). For @lutzhorn’s question, I want to know how the code work like that.

It is an object of type ArgErr which is returned and e is assigned to this. You can put an extra line which prints the object, its type and it’s string representation. Like this: Go Playground - The Go Programming Language (line 70)

Error handling and Go - The Go Programming Language says this

The fmt package formats an error value by calling its Error() string method.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.