Q about defer

173 views
Skip to first unread message

Денис Мухортов

unread,
Dec 24, 2021, 8:34:58 AM12/24/21
to golang-nuts
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?

peterGo

unread,
Dec 24, 2021, 9:39:32 AM12/24/21
to golang-nuts
The Go Programming Language Specification

https://go.dev/ref/spec

Defer statements  

https://go.dev/ref/spec#Defer_statements

Peter

Kevin Chowski

unread,
Dec 24, 2021, 12:49:38 PM12/24/21
to golang-nuts
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


Kevin Malachowski

unread,
Dec 24, 2021, 5:13:05 PM12/24/21
to golang-nuts
Actually, this part is a bit more relevant:

"That is, if the surrounding function returns through an explicit return statement, deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller."

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/CS-YQw_xAtc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@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 all
Reply to author
Forward
0 new messages