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:
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
}
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:
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 && age 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3