"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do `defer` Statements Affect Return Values in Go Based on Variable Declaration?

How Do `defer` Statements Affect Return Values in Go Based on Variable Declaration?

Posted on 2025-03-23
Browse:668

How Do `defer` Statements Affect Return Values in Go Based on Variable Declaration?

Understanding Functional Modifications in Golang with defer

In Golang, defer allows developers to set up functions to execute after a function concludes, enabling post-execution cleanups. However, issues can arise when attempting to modify variable values declared in different ways within the same function.

Consider the following code example:

func c(i int) int {
    defer func() { i   }()
    return i
}

func c1() (i int) {
    defer func() { i   }()
    return i
}

func c2() (i int) {
    defer func() { i   }()
    return 2
}

In c(0), due to i being an input parameter, the returned value is unaffected by the deferred increment, resulting in a print output of 0.

In c1(), i is the named result parameter, where the return value is explicitly assigned to it prior to deferred function execution. Thus, the deferred increment affects the returned value, giving an output of 1.

However, in c2(), even though i is returned explicitly as 2, the deferred increment modifies the result parameter, resulting in a return value of 3.

The specification clarifies this behavior:

Return statements:
A "return" statement that specifies results sets the result parameters before any deferred functions are executed.

For functions with named result parameters, the returned values are always the values of those variables, but return statements can assign new values to these parameters. Deferred functions can further modify these parameters after the return statement.

This principle applies to both functions and methods, where deferred functions can access and modify named result parameters before they are returned. Therefore, it's crucial to consider how variable declarations and deferred function modifications impact the final returned values.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3