Typo in exemple code of the Go Blog?


(yves) #1

Here the link to the page in question: https://blog.golang.org/defer-panic-and-recover

The exemple code as is in the page is

func c() (i int) {
    defer func() { i++ }()
    return 1
}

And I think it should return iinstead. Am I wrong?
So it should be:

func c() (i int) {
    defer func() { i++ }()
    return i
}

(Alberto Bregliano) #2

Yeah I believe you are right


(nathankerr) #3

The text above that code says:

In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:

At the beginning of c(0), i is 0 (the zero value for an int). For the function to return 2, i needs to be 1 so the increment done in the deferred function increases the returned value (i) to 2. return 1 sets i to 1.

Since a return statement is required for functions that return values, this single line return 1 is the easiest way to both set i to 1 (as required by the text) and return.


(yves) #4

Thank you very much nathankerr. Your reply made me realize that in func c() (i int) { the (i int) part is actually declaring the returning variable. It is not, actually, the parameter part in the declaration, which is empty.

I completely overlooked that. And frankly I find it quite misleading/confusing. It is something to look after in production code I guess. My eyes are so used to C code (or whatever languages), it did not see that caveat.

Thank you. :slight_smile:


(nathankerr) #5

I try to use named return values only when they are needed, such as when handling errors in defer or recovering from panic and a return value needs to be set.


(system) #6

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