Specifically, this part from the #Defer_statements linked by Peter:

"For instance, if the deferred function is a function literal and the 
surrounding function has named result parameters that are in scope within 
the literal, the deferred function may access and modify the result 
parameters before they are returned."

In the case of `test`, the x variable is a named return variable so the 
defer is able to modify the returned value after the `return` but before 
the caller receives the result.

In the case of `anotherTest`, the x variable is a local variable; when the 
`return x` is executed, the value of `x` is effectively copied into a new 
location that is distinct from the `x` variable, so the defer is modifying 
a different value than the one that is actually being returned.

As a third example, note that you can also return a value directly even 
when using named return variables, which will immediately set the return 
variables to the values in the return statement before defers are 
executed: https://play.golang.com/p/JduT2zD5Nah


On Friday, December 24, 2021 at 7:39:32 AM UTC-7 peterGo wrote:

> The Go Programming Language Specification
>
> https://go.dev/ref/spec
>
> Defer statements  
>
> https://go.dev/ref/spec#Defer_statements
>
> Peter
>
> On Friday, December 24, 2021 at 8:34:58 AM UTC-5 muhorto...@gmail.com 
> wrote:
>
>> https://play.golang.com/p/lypWMc6Kuff
>> Why do we get 2 in test() and 1 in anotherTest()? Is it related to the 
>> definition of the variable in the output? 
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/96cc1555-2b1e-4094-ae16-a9168acbe1a1n%40googlegroups.com.

Reply via email to