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.

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