Typo in exemple code of the Go Blog?

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
}

Yeah I believe you are right

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.

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:

1 Like

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.

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