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

(cphh) #1

Considering the example 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.

(Lutz Horn) #2

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

(cphh) #3

check my edited question

(Norbert Melzer) #4

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

Could you please answer @lutzhorn’s quetsions:

(cphh) #5

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.

(Johan Dahl) #6

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: (line 70) says this

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