We can delay a function call to the end of the current scope by using the defer keyword. defer tells Go to run a function, but at the end of the current function. This is useful for logging, file writing, and other utilities.

func calculateTaxes(revenue, deductions, credits float64) float64 { defer fmt.Println("Taxes Calculated!") taxRate := .06143 fmt.Println("Calculating Taxes") if deductions == 0 || credits == 0 { return revenue * taxRate } taxValue := (revenue - (deductions * credits)) * taxRate if taxValue >= 0 { return taxValue } else { return 0 } }

In the above example, when we call calculateTaxes() we immediately defer a message, "Taxes Calculated!". This does not print until the end of the function (after the taxes have been calculated and are about to be returned). Normally, we would consider adding fmt.Println("Taxes Calculated!") at the end of calculateTaxes(). But, we have multiple return statements in our code, instead of adding a print statement right before each return, we use defer and it prints regardless of when our function ends. The output would read:

Calculating Taxes Taxes Calculated!



We need to be disconnecting from the database that we’re connecting to to get our cool information! Use defer to call disconnectDatabase() every time queryDatabase() finishes running.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?