How defer Keyword Works in Go
In Go, the defer keyword allows you to delay the execution of a function or statement until the surrounding function returns. However, the value and parameters of the deferred function are evaluated immediately and bound to the function call at the time of the defer statement.
Understanding the Defer Evaluation Order
For example, the following code:
defer fmt.Println("Your age is:", getAge(age))
defers the execution of the function fmt.Println and binds the value of age at the time of the defer statement. However, the actual fmt.Println function call will be executed in reverse order just before the surrounding function returns.
Application in a Ticket Price Calculation
In your case, you want to calculate the ticket price based on the user's age:
defer fmt.Println("Your ticket price is:", printTicket(age, ticketPrice))
Here, the defer statement binds the value of age and ticketPrice at the time of the defer statement. When the main function returns, printTicket will be called with the bound values of age and ticketPrice. However, since only the if statement for age <= 13 is being executed, it only prints 9.99.
Resolving the Issue
To fix the issue, ensure that all necessary conditions in printTicket are evaluated before the function is deferred. Here's a modified version:
defer fmt.Println(*age) if *age <= 13 { ticketPrice = 9.99 } else if *age > 13 && *age < 65 { ticketPrice = 19.99 } else if *age >= 65 { ticketPrice = 12.99 } defer fmt.Println(ticketPrice)Now, both fmt.Println(*age) and fmt.Println(ticketPrice) will be deferred and executed in reverse order, displaying the correct age and ticket price.
The above is the detailed content of Why Does My Defer Statement Not Produce the Expected Ticket Price in Go?. For more information, please follow other related articles on the PHP Chinese website!