Home > Backend Development > Golang > How does defer work with function parameters in Go?

How does defer work with function parameters in Go?

Mary-Kate Olsen
Release: 2024-11-04 03:49:02
Original
299 people have browsed it

How does defer work with function parameters in Go?

Understanding the intricacies of "defer" in Go

Defer in Go is a powerful keyword that allows you to defer the execution of a function call until the enclosing function returns. However, when working with defer, it's crucial to grasp the evaluation order of function parameters and return values.

Evaluation Order and Defer

According to the documentation on Defer_statements, each time a "defer" statement is executed,"the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked." This means that when you call a deferred function, the function parameters are evaluated first, and then the actual function is invoked during the function's return.

Scenario

Let's delve into a specific example where you're having trouble getting the ticket price to calculate correctly based on the user's age. Your code defines a deferred call to printTicket with an argument of ticketPrice. You're expecting ticketPrice to be set according to the provided age and return the appropriate ticket price.

The Issue

The problem arises because you're trying to pass an uninitialized "ticketPrice" to printTicket. When the deferred call to printTicket is executed during main's return, the uninitialized "ticketPrice" will result in a default zero value, causing only the 9.99 price to be printed.

Solution

To resolve this, you should initialize "ticketPrice" to the correct value before deferring the call to printTicket. Alternatively, you could use a modified function calling syntax that allows you to pass "ticketPrice" by reference, ensuring that the deferred call gets the updated value.

Example

Here's a modified version of your code that demonstrates the correct usage of defer:

<code class="go">package main

import "fmt"

func printTicket(age int) float64 {
    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 main() {
    var age int
    defer fmt.Println("...order is 4...Your age is:", getAge(&age))
    // Modify the calling syntax here:
    var ticketPrice = 0.0
    defer fmt.Println("...order is 3...Your ticket price is:", printTicket(age, &ticketPrice)) 
}

func getAge(age *int) int {
    fmt.Println("...order is 1...")
    fmt.Print("Enter age=")
    fmt.Scanln(age)
    return *age
}</code>
Copy after login

With these modifications, the "ticketPrice" variable will be properly initialized before the "printTicket" call, ensuring that the correct ticket price is calculated and printed.

The above is the detailed content of How does defer work with function parameters in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template