Understanding the Functionality of Go's Defer Keyword
When working with Go, understanding the behavior of the defer keyword is crucial. This keyword allows developers to defer the execution of a function until the surrounding function returns. However, it's important to note that the function's value and parameters are evaluated when the defer statement executes.
Example: Evaluating Defer Order
To illustrate this, consider the following code:
<code class="go">package main import "fmt" func main() { defer having()(fun("with Go.")) fmt.Print("some ") // evaluation order: 3 } func having() func(string) { fmt.Print("Go ") // evaluation order: 1 return funWithGo } func fun(msg string) string { fmt.Print("have ") // evaluation order: 2 return msg } func funWithGo(msg string) { fmt.Println("fun", msg) // evaluation order: 4 }</code>
In this example, the code is executed in the following order:
Applying the Defer Principle
To resolve the issue mentioned in the original query, we can use the defer keyword to correctly print the ticket price based on the entered age. Below is a modified version of the code:
<code class="go">package main import "fmt" func main() { age := 999 defer fmt.Println("Your age is:", getAge(&age)) // defer printing the age defer fmt.Println("Your ticket price is:", getTicketPrice(age)) // defer printing the ticket price } func getTicketPrice(age int) float64 { // Calculate ticket price based on age // logic can be customized here fmt.Println("...order is 2...") switch { case age <= 13: return 9.99 case age > 13 && age < 65: return 19.99 default: return 12.99 } } func getAge(age *int) int { fmt.Println("...order is 1...") fmt.Print("Enter age=") fmt.Scanln(age) return *age }</code>
In this modified code, we correctly leverage the defer keyword to ensure that the age and ticket price are printed after the respective functions have executed, resolving the initial issue.
The above is the detailed content of How Does Go's Defer Keyword Work in Function Execution Order?. For more information, please follow other related articles on the PHP Chinese website!