"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Does Go\'s Defer Keyword Work in Function Execution Order?

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

Published on 2024-11-06
Browse:125

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:

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:

  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:

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.

Latest tutorial More>

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