Home >Backend Development >Golang >How Do Go\'s `defer` Statements Affect Variables Declared as Input Parameters vs. Named Result Parameters?

How Do Go\'s `defer` Statements Affect Variables Declared as Input Parameters vs. Named Result Parameters?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 20:11:12218browse

How Do Go's `defer` Statements Affect Variables Declared as Input Parameters vs. Named Result Parameters?

Defer Behavior for Variables Declared Differently in Golang

Functions with named result parameters behave differently when using the defer statement compared to functions with input parameters. In this example, we examine these differences:

package main

import (
    "fmt"
)

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
}

func main() {
    fmt.Println(c(0)) // Prints 0
    fmt.Println(c1()) // Prints 1
    fmt.Println(c2()) // Prints 3
}

c(i int):

In this case, i is an incoming parameter. The return value is evaluated before the deferred function runs, so incrementing i after the return has no effect.

c1():

Here, i is the result parameter. The return i statement assigns the value of i to the return value. However, deferred functions can modify return variables. In this case, the deferred function increments i, resulting in a return value of 1.

c2():

Similar to c1(), the return 2 statement assigns 2 to i. However, in this case, the deferred function executes after the return statement, resulting in a return value of 3.

In summary, when working with named result parameters in Go, it's important to remember that deferred functions can modify their values even after the return statement. This behavior is explicitly mentioned in the Go specification and can be used to alter return values when necessary.

The above is the detailed content of How Do Go\'s `defer` Statements Affect Variables Declared as Input Parameters vs. Named Result Parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn