My question is about the different named return value vs normal return value.
my code
package main
import "fmt"
func main() {
f := fmt.Println
f(a())
f(b())
}
func a() int {
i := 0
defer func() {
i += 1
fmt.Println("a defer : ", i)
}()
return i
}
func b() (i int) {
i = 0
defer func() {
i += 1
fmt.Println("b defer : ", i)
}()
return i
}
the result:
the a function return 0
the b function reutrn 1
Why?
The named return value also allocates a variable for the scope of your function.
func a() int
: While you already return the value of i = 0
, but since no named values was defined the static value got returned. So even though you're increasing i
in the deferred function it doesn't affect the returned value.
func b() (i int)
: The variable i
is allocated (and already initialized to 0
). Even though the deferred function runs after the i = 0
was returned the scope is still accessible and thus still can be changed.
Another point of view: you can still change named return values in deferred functions, but cannot change regular return values.
This especially holds true in the following example:
func c() (i int) {
defer func() {
i = 1
fmt.Println("c defer : ", i)
}()
return 0
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With