Home > Backend Development > Golang > Does Go Capture For-Loop Variables as Values or Variables?

Does Go Capture For-Loop Variables as Values or Variables?

DDD
Release: 2024-12-24 01:09:17
Original
175 people have browsed it

Does Go Capture For-Loop Variables as Values or Variables?

Captured Closure (for-loop variables) in Go

Are for-loop variables in Go not captured as locally assigned closure variables?

No, captured for-loop variables in Go are by default captured as values, not variables. This behavior differs from languages like C#, which requires extra syntax to capture variables instead of values.

Example: Capturing Loop Variables as Values

package main

import "fmt"

func main() {
    a := 1
    b := func() { fmt.Println(a) } // b captures the value of a, not the variable itself
    a++
    b() // prints 1, not 2
}
Copy after login

In this example, the function b captures the value of a at the time it is defined, rather than retaining a reference to the variable itself. Consequently, any changes made to a after defining b will not be reflected in the value printed by b.

Example: Capturing Loop Variables as Variables

However, it is possible to capture loop variables as variables by using a closure syntax that creates a new scope for each iteration:

package main

import "fmt"

func main() {
    a := 1
    for a < 10 {
        b := func() { fmt.Println(a) } // b captures the variable a in a new scope
        a++
        b() // prints 2, 3, 4, ..., 10
    }
}
Copy after login

In this example, the func keyword is used to create a closure for each iteration of the loop. This technique ensures that each closure captures a unique reference to the loop variable, allowing us to observe the value of a as it changes within the loop.

Conclusion

Go capturaes for-loop variables as values by default, but it also provides a closure syntax that allows for-loop variables to be captured as variables. Understanding this distinction is crucial for avoiding confusion and writing correct and efficient Go code.

The above is the detailed content of Does Go Capture For-Loop Variables as Values or Variables?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template