Home > Backend Development > Golang > How Does Defer Capture Parameters in Go Closures?

How Does Defer Capture Parameters in Go Closures?

Mary-Kate Olsen
Release: 2024-11-10 17:53:02
Original
383 people have browsed it

How Does Defer Capture Parameters in Go Closures?

Defer Capture in Go with or Without Parameters

In Go, the defer keyword can be used to defer the execution of a function until the surrounding function returns. When used with anonymous closures, however, the behavior can vary depending on how the closure captures its parameters.

Consider the following code:

import "fmt"

func main() {
    var whatever [5]struct{}

    for i := range whatever {
        fmt.Println(i)
    } // part 1

    for i := range whatever {
        defer func() { fmt.Println(i) }()
    } // part 2

    for i := range whatever {
        defer func(n int) { fmt.Println(n) }(i)
    } // part 3
}
Copy after login

Part 2: Closure Without Parameter

In part 2, the closure does not capture any parameters. This means that when the closure is executed, the variable i has the value that it had when the defer statement was executed. In this case, i will have the value of the last iteration of the for loop, which is 4. Consequently, the output of part 2 will be:

4 4 4 4 4
Copy after login

Part 3: Closure With Parameter

In part 3, the closure captures the parameter n, which is initialized to the value of i when the closure is created. This means that when the closure is executed, n will have the value that it had when the defer statement was executed. In this case, each closure captures a different value of i, resulting in the output:

4 3 2 1 0
Copy after login

Conclusion

The key difference between part 2 and part 3 is that part 2 captures the i variable while part 3 does not. This affects the behavior of the closure when it is executed, leading to different outputs.

The above is the detailed content of How Does Defer Capture Parameters in Go Closures?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template