Defer Usage Clarification
When working with functions that defer execution, it's important to consider the evaluation of parameters at the time of deferment. As documented, "defer" saves the evaluated function value and parameters when the statement is executed.
Initial Approach
In the provided code, a simple loop is used to increment a variable x. However, when the deferred fmt.Println(x) is executed, it prints a zero even though the variable x has gone through multiple increments within the loop. This is because x is evaluated when the defer is executed, not when it is actually called.
Alternate Solutions
1) Anonymous Function:
Introducing an anonymous function allows separation from the current function's parameters. When the anonymous function executes, it accesses and prints the updated value of x.
2) Pointer:
Using a pointer points to x. It does not evaluate x when the defer statement is executed, but only the address of x. This approach requires a helper function to print the pointed value manually.
3) Custom Type:
Creating a custom type with a custom String() method provides a high-level way to access the value of a pointer. When using fmt.Println() with an object of this custom type, it automatically calls the String() method to retrieve the desired value.
4) Wrapping:
Wrapping x into a slice during the defer statement results in a descriptor that points to the underlying array. When the slice is printed using fmt.Println(), the updated value of x is accessed and printed. By extending this to arrays or other similar types, it becomes possible to print the pointed content.
The above is the detailed content of Why Does `defer` in Go Print the Initial Value of a Variable Despite Subsequent Changes?. For more information, please follow other related articles on the PHP Chinese website!