SoFunction
Updated on 2025-04-07

go closure case sample code

The code snippet you mentioned is an anonymous function, and it is executed immediately after definition (i.e. IIFE, executing the function expression immediately). This anonymous function internal pairz = x / yThe reason why the assignment operation can affect external variables is the scope rules and closure mechanism of the Go language.

explain

  • Closure mechanism

    • Anonymous functions can access variables in the scope they are defined. This feature is called closure. In your example, anonymous function captures externalzxandyVariable.
  • Variable scope

    • ifzxandyis a variable declared outside an anonymous function (for example, inmainin function), then these variables are globally visible, or at least visible in the scope chain of anonymous functions.
    • When you modify these variables inside anonymous functions, you are actually modifying the original memory location of these variables, so these changes are reflected outside.
  • Execute function expressions immediately (IIFE)

    • An anonymous function is executed immediately after it is defined, which means that its side effects (such as variable assignments) will take effect immediately.

Sample code analysis

Assume the complete code is as follows:

package main
import "fmt"
func main() {
    var x, y, z int
    x = 10
    y = 2
    func() {
        defer func() {
            if r := recover(); r != nil {
                ("recovered from ", r)
            }
        }()
        z = x / y
    }()
    ("Result:", z) // Output: Results: 5}

In this example:

  • xyandzIt's inmainVariables declared in the function.
  • Anonymous functions capture these variables and perform them inside themz = x / yCalculation.
  • becausezIt's inmainDeclared in the function, so the anonymous function internallyzThe modification will affectmainin the functionz

Summary of key points

  • Closure: Anonymous functions can access and modify variables in the scope when their definitions are located.
  • Execute now: Execute immediately after the anonymous function is defined, and its side effects will take effect immediately.
  • Variable scope: If variables are declared in an external scope, the anonymous function can access and modify these variables internally.

Things to note

  • make sureyNot zero to avoid zero-dividing errors. You can add check logic to prevent this from happening.
func main() {
    var x, y, z int
    x = 10
    y = 2
    func() {
        defer func() {
            if r := recover(); r != nil {
                ("recovered from ", r)
            }
        }()
        if y == 0 {
            panic("division by zero")
        }
        z = x / y
    }()
    ("Result:", z)
}

This ensures that the program isyWhen it is zero, it will not crash and can be recovered correctly.

This is all about this article about go closure case. For more related go closure case content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!