Home > Backend Development > Golang > How Does Go\'s Defer Keyword Work in Function Execution Order?

How Does Go\'s Defer Keyword Work in Function Execution Order?

Susan Sarandon
Release: 2024-10-29 20:32:03
Original
1085 people have browsed it

How Does Go's Defer Keyword Work in Function Execution Order?

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>
Copy after login

In this example, the code is executed in the following order:

  1. having function is evaluated and returns a function that takes a string as input (evaluation order: 1)
  2. fun function is evaluated with the "with Go." string as input (evaluation order: 2)
  3. fmt.Print("some ") is executed (evaluation order: 3)
  4. defer calls funWithGo function with the result from fun (evaluation order: 4)

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>
Copy after login

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!

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