Home >Backend Development >Golang >How to Correctly Use `defer` in Go with Modified Variables?

How to Correctly Use `defer` in Go with Modified Variables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 09:54:14412browse

How to Correctly Use `defer` in Go with Modified Variables?

Defer Usage Clarification

In Go, the "defer" statement allows us to schedule a function to be executed just before the surrounding function returns. However, this can lead to confusion when dealing with variables that are modified within the enclosing function.

Original Issue

Consider the following function:

func printNumbers() {
  var x int

  defer fmt.Println(x)

  for i := 0; i < 5; i++ {
    x++
  }
}

According to the Go specification, when a "defer" statement is executed, the function value and parameters are evaluated and stored for later execution. This means that when the function is eventually called, the value of x will still be 0 because it was evaluated at the time of deferral.

Solution with Anonymous Function

To resolve this issue, we can use an anonymous function within the "defer" statement:

defer func() { fmt.Println(x) }()

Here, x is not a parameter of the anonymous function, so it will not be evaluated when the "defer" statement is executed. Instead, the value of x will be captured at the time the anonymous function is called, ensuring that the most up-to-date value is printed.

Alternative Solutions

  1. Using a Pointer:

    var x int
    
    defer func() { fmt.Println(&x) }()

    This approach uses a pointer to x as the parameter of the deferred function. When the "defer" statement is executed, only the pointer is evaluated, not the value of x. When the deferred function is called, it will access the current value of x through the pointer.

  2. Using a Custom Type:

    type MyInt int
    
    func (m *MyInt) String() string {
      return strconv.Itoa(int(*m))
    }
    
    var x MyInt
    
    defer fmt.Println(&x)

    This solution is similar to the pointer approach but uses a custom type (MyInt) that implements the String() method. By implementing String(), we can control how the value of x is printed.

  3. Using a Slice:

    var x []int
    
    defer fmt.Println(x)

    Slicing is a descriptor type in Go, which means that its value is a reference to an underlying array. When we defer a slice, only the reference is evaluated, not the actual array elements. As a result, any changes made to the slice elements after the deferral will be reflected in the printed output.

  4. Wrapping in a Struct:

    type Wrapper struct {
      Value int
    }
    
    var x Wrapper
    
    defer fmt.Println(&x)

    This approach is similar to using a pointer, but we wrap the value in a struct to avoid having to dereference the pointer in the deferred function.

The above is the detailed content of How to Correctly Use `defer` in Go with Modified Variables?. 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