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

Kawaii Halloween Decor Without Gore or Jump Scares

Kawaii Halloween Decor Without Gore or Jump Scares

Create a gentle Halloween look with pastel colors, friendly ghosts, easy no-carve accents, and practical safety tips for your home.

Desk Decorating Ideas for a Spooky Office Cubicle

Desk Decorating Ideas for a Spooky Office Cubicle

Create a spooky office cubicle with Halloween desk decor ideas that keep your workspace usable, tidy, and mindful of workplace safety.

Pop Culture Costume Ideas That Will Dominate Halloween 2026

Pop Culture Costume Ideas That Will Dominate Halloween 2026

Plan a recognizable Halloween 2026 look with pop culture costumes inspired by Spider-Man, Supergirl, Toy Story 5, Moana, Mario, and Wednesday.

Leftover Halloween Candy and Pumpkins: What to Do Next

Leftover Halloween Candy and Pumpkins: What to Do Next

Sort leftover Halloween candy safely, share or repurpose sealed treats, and choose food use or compost for pumpkins based on their condition.

What Not to Wear: A Guide to Professional Workplace Halloween Etiquette

What Not to Wear: A Guide to Professional Workplace Halloween Etiquette

Compare workplace Halloween costume choices by respect, dress code, mobility, and safety—and learn when a subtle accessory or a policy check is the better option.

Couples Costume Ideas for 2026: Iconic Pairs and Clever Tropes

Couples Costume Ideas for 2026: Iconic Pairs and Clever Tropes

Find a couples costume that fits your style, budget, and comfort level, from Addams Family classics to original inside-joke duos.

Last-Minute High School Halloween Costumes That Take 5 Minutes

Last-Minute High School Halloween Costumes That Take 5 Minutes

Need a last-minute high school Halloween costume? Compare 10 easy closet-based ideas by prep time, comfort, school-day practicality, and simple safety checks.

When to Start Decorating for Halloween in 2026

When to Start Decorating for Halloween in 2026

Use a simple 2026 Halloween decorating timeline for indoor décor, outdoor displays, and fresh pumpkins, with practical adjustments for weather and events.

5 Halloween Cocktails That Are Easy to Serve at Your 2026 Bash

5 Halloween Cocktails That Are Easy to Serve at Your 2026 Bash

Mix five vivid, approachable Halloween cocktails with measured recipes, simple prep tips, and an alcohol-free option for your party guests.

15 HR-Approved Office Halloween Costumes for 2026

15 HR-Approved Office Halloween Costumes for 2026

Find 15 office-friendly Halloween costume ideas for 2026, with practical checks for dress codes, respectful themes, comfort, and workplace safety.