How Named Return Values Interact with Deferred Functions
In Go, named return values allow functions to specify return values by name instead of using positional arguments. The interaction between named return values and deferred functions can be confusing, as seen in the following example:
func c() (i int) { defer func() { i++ }() return 1 }
This function is expected to return 2, according to the documentation: "Deferred functions may read and assign to the returning function's named return values." However, in this case, the function returns 1, which seems to contradict the documentation.
To understand this behavior, it's important to remember that a return statement without arguments returns the named return values, known as a "naked" return. The example code returns 1 because it uses return 1, which explicitly assigns the return value to 1.
The deferred function is executed after the return statement, incrementing i. However, this increment does not affect the named return value i, as it effectively assigns the new value to a local variable within the deferred function.
This is because return 1 is equivalent to:
i = 1 return
In a function with a named return value variable i, the assignment i = 1 sets the named return value, while the return statement simply exits the function, allowing the deferred function to execute and modify the local i variable without affecting the named return value.
Therefore, the function c actually returns 1, despite the use of a deferred function to increment i.
The above is the detailed content of Why Does a Deferred Function Fail to Increment a Named Return Value in Go?. For more information, please follow other related articles on the PHP Chinese website!