Defer Keyword in Golang

In Go, defer statements delay execution of a function or method or an anonymous method until the surrounding function returns. In other words, the arguments to the defer function or method are evaluated immediately, but they do not execute until the surrounding function returns. You can create a deferred method, function, or anonymous function using the defer keyword.

Defer Keyword in Golang

Syntax:

// Hàm
defer func func_name(parameter_list Type)return_type{
// Code
}

// Phương thức
defer func (receiver Type) method_name(parameter_list){
// Code
}

defer func (parameter_list)(return_type){
// code
}()

Important Note:

  • In Go language, multiple defer statements are allowed in the same program and they are executed in LIFO (Last-In, First-Out) order as shown in Example 2.
  • In defer statements, the arguments are evaluated when the defer statement is executed, not when it is called.
  • Defer statements are often used to ensure that files are closed when their need ends, or to close channels, or to catch problems in the program.

Now let's look at an example to understand better.

Example 1:

// Chương trình Go minh họa
// khái niệm của lệnh defer
package main

import "fmt"

// Các hàm
func mul(a1, a2 int) int {

	res := a1 * a2
	fmt.Println("Result: ", res)
	return 0
}

func show() {
	fmt.Println("Hello!, Quantrimang.com")
}

// Hàm chính
func main() {

	// Gọi hàm mul() 
	// Tại đây hàm mul hoạt động
	// như một hàm bình thường
	mul(23, 45)

	// Gọi hàm mul()
	// Dùng từ khóa defer 
	// Hàm the mul() 
	// là hàm defer
	defer mul(23, 56)

	// Gọi hàm show() 
	show()
}

Result:

Result:  1035
Hello!, Quantrimang.com
Result:  1288

Explanation: In the above example, we have two functions named mul() and show() . While the show() function is called normally in the main() function , the mul() function is called in two different ways:

  • First, we call the mul function normally (without the defer keyword), i.e. mul(23, 45) and it executes when the function is called (Output: Result: 1035).
  • Second, we call the mul() function as a defer function using the defer keyword, i.e. defer mul(23, 56) and it executes (Output: Result: 1288) when all the surrounding methods return.

Example 2:

// Minh họa chương trình Go
// dùng nhiều lệnh defer, để minh họa chính sách LIFO 
package main

import "fmt"

// Các hàm
func add(a1, a2 int) int {
	res := a1 + a2
	fmt.Println("Result: ", res)
	return 0
}

// Hàm chính
func main() {

	fmt.Println("Start")

	// Nhiều lệnh defer
	// Triển khai theo thứ tự LIFO 
	defer fmt.Println("End")
	defer add(34, 56)
	defer add(10, 10)
}

Result:

Start
Result:  20
Result:  90
End

Leave a Comment

Can Large Format Printing Ever Be Sustainable? The Answer Is Changing Fast

Can Large Format Printing Ever Be Sustainable? The Answer Is Changing Fast

Large format printing has long faced criticism for its environmental impact. Traditional substrates, solvent-based inks, and short-lived promotional campaigns have all contributed to the perception that eye-catching graphics come at a high environmental cost.

What Young Riders Should Know About Moving Their Motorcycles Across Cities

What Young Riders Should Know About Moving Their Motorcycles Across Cities

Long-distance travel can involve heavy traffic, changing weather conditions, and rider fatigue. If you are also dealing with the responsibilities of moving home, such as packing belongings or coordinating accommodation, a long ride may add unnecessary pressure to an already busy schedule.

Solving Microsoft Teams Shortcut Error Not Opening

Solving Microsoft Teams Shortcut Error Not Opening

Tired of Microsoft Teams shortcut error preventing you from opening the app? Follow our expert, step-by-step guide with the latest fixes for instant resolution. Works on Windows, Mac & web – no tech skills needed!

Solving Microsoft Teams Task Management Sync Error

Solving Microsoft Teams Task Management Sync Error

Tired of Microsoft Teams Task Management Sync Error halting your workflow? Follow our proven, step-by-step fixes to resolve sync issues fast and restore seamless task collaboration. No tech expertise needed!

Troubleshooting Microsoft Teams Wiki Error Formatting

Troubleshooting Microsoft Teams Wiki Error Formatting

Struggling with Microsoft Teams Wiki Error Formatting? This step-by-step guide reveals proven fixes for common wiki tab issues, ensuring smooth editing and collaboration in Teams. Get back to productive wikis fast!

How to Fix Microsoft Teams Installation Error for Linux

How to Fix Microsoft Teams Installation Error for Linux

Struggling with Microsoft Teams installation error on Linux? Discover step-by-step fixes for Ubuntu, Fedora & more. Resolve dependency issues, crashes, and errors quickly with our ultimate guide. Get Teams running smoothly today!

Solving Microsoft Teams Error Page Not Loading

Solving Microsoft Teams Error Page Not Loading

Struggling with Microsoft Teams "Error Page" not loading? Get step-by-step fixes for desktop, web, and mobile. Solve Microsoft Teams Error Page issues quickly and resume seamless teamwork today.

Solving Microsoft Teams Error Screenshot Issues

Solving Microsoft Teams Error Screenshot Issues

Tired of Microsoft Teams "Error Screenshot" blocking your workflow? Get proven, step-by-step solutions to resolve screenshot errors in Teams instantly and boost productivity. No tech skills needed!

How to Fix Microsoft Teams Error U User

How to Fix Microsoft Teams Error U User

Tired of Microsoft Teams "Error U" User blocking your chats? Get proven, step-by-step fixes to clear cache, reset, and restore seamless collaboration instantly.

Where are Microsoft Teams Registry Keys Located on Windows 11?

Where are Microsoft Teams Registry Keys Located on Windows 11?

Unlock the precise locations of Microsoft Teams registry keys on Windows 11. Step-by-step guide to find, access, and safely tweak them for optimal performance and troubleshooting. Essential for IT pros and Teams enthusiasts.