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
Sign up and earn $1000 a day ⋙

Leave a Comment

Function arguments in Golang

Function arguments in Golang

Go supports two main ways to pass arguments: Pass by Value and Pass by Reference. Go uses pass by value by default.

Function returning multiple values ​​in Golang

Function returning multiple values ​​in Golang

In Go language, you are allowed to return multiple values ​​from a function, using the return statement. In other words, in a function, a return statement can return multiple values.

Switch Statement in Go

Switch Statement in Go

Golang like most other programming languages ​​has switch statement. Here is how to use switch statement in Golang.

Cases to know when using selection statements in Golang

Cases to know when using selection statements in Golang

In this article, we will learn how to use default case to avoid deadlock. But first, we will learn what is deadlock case when using select command in Golang?

Anonymous structures and fields in Golang

Anonymous structures and fields in Golang

Anonymous structs in Golang are temporary structures with no names used for one-time purposes, while anonymous fields allow embedding of unnamed fields.

How to use Rune in Golang

How to use Rune in Golang

What is Rune in Golang? How to use Rune in Golang? This article will give you the answer.

How to use operators in Golang

How to use operators in Golang

Operators allow us to perform different types of operations on operands. In Go language, operators can be classified based on their different functions.

Void identifier in Golang

Void identifier in Golang

_(underscore) in Golang is called Blank Identifier. Identifier is a user-defined name of program elements used for identification purposes.

How to create basic program in Golang

How to create basic program in Golang

Hello, World! is the first basic program in any programming language. You can write this first program in Golang by following the steps below.

How to Install Go on Windows

How to Install Go on Windows

Golang can be easily installed on Windows. Here is a step-by-step guide to install Golang on Windows.

Methods with the same name in Golang

Methods with the same name in Golang

Golang allows creating two or more methods with the same name in the same package, but the receivers of these methods must be of different types.

Functions in Go

Functions in Go

In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time.

Variable Scope in Go

Variable Scope in Go

The scope of a variable in Golang determines which part of the program the variable is accessible to. In Go, all identifiers have a lexical scope that is determined at compile time.

Control Statements in Golang (if, if-else, Nested-if)

Control Statements in Golang (if, if-else, Nested-if)

What conditional statements does Golang have? How to use conditional statements in Go programming? Let's find out together!

Short variable declaration operator in Go

Short variable declaration operator in Go

The short variable declaration operator (:=) in Golang is used to create variables with a proper name and initial value. Here is what you need to know about the short variable declaration operator in Golang.

6 Easiest Ways to Add Music to Videos on Your Computer

6 Easiest Ways to Add Music to Videos on Your Computer

Windows 10 has built-in video and image editor right on your computer with simple customizations so you can process videos without needing video editing software.

Instructions for creating mind maps in Word

Instructions for creating mind maps in Word

Mind maps are extremely useful when we need to remember information because the content is designed in the most visual style. Below are instructions for creating a mind profile in Word.

9 Apps to Add to Control Center iOS 18

9 Apps to Add to Control Center iOS 18

With iOS 18, Apple has made it even easier to customize Control Center and even your lock screen with support for widgets from third-party apps.

5 unique features of the Pixel 9 Pro Fold

5 unique features of the Pixel 9 Pro Fold

Google launched the Pixel 9 Pro Fold at its Made by Google event in August 2024. While it has a few improvements over its predecessor to compete with the Galaxy Z Fold 6 and OnePlus Open, these are the features that many people are most excited to try.

All the latest codes for Otherworld: Light and Magic

All the latest codes for Otherworld: Light and Magic

Different World: Light and Magic gives players a series of attractive rewards including Star Diamonds, Sparkling Stardust, EXP, Soul Stones, and Summon Cards in the giftcode.

Latest Ninja Legend Code 4/2025

Latest Ninja Legend Code 4/2025

Get the Ninja Legend giftcode now to receive attractive rewards.

Things that silently damage the house that few people realize

Things that silently damage the house that few people realize

These seemingly normal actions can cause damage to your home in the long run. Here are some things to avoid to keep your home neat, clean and durable.

Microsoft announces end of support date for Office 2016 and 2019 applications and servers

Microsoft announces end of support date for Office 2016 and 2019 applications and servers

Microsoft has finally officially announced the planned end of support (EOS) for the Office 2016 and Office 2019 application ecosystem.

5 parameters that are no longer important on smartphones

5 parameters that are no longer important on smartphones

When choosing to buy a new phone, the first thing many people often do is refer to the specification table. This is basically not wrong, however, there are some details that you should not pay too much attention to because they no longer reflect the actual experience.

Microsoft 365 will disable ActiveX due to excessive hacker abuse

Microsoft 365 will disable ActiveX due to excessive hacker abuse

Microsoft Office has supported ActiveX for years as an option for document extensibility and automation, but it's also a serious security vulnerability.

MIUI 12.5 Info: Release Date, Supported Devices, and New Features

MIUI 12.5 Info: Release Date, Supported Devices, and New Features

MIUI 12.5 will be based on Android 11 and also comes with additional features in Xiaomi smartphones.

How to Completely Delete Any Windows File Using SDelete

How to Completely Delete Any Windows File Using SDelete

To ensure that files are deleted permanently, you can use SDelete. This command line utility securely deletes data, making it unrecoverable.

Semiconductor industry revenue to increase 18% in 2024, Samsung regains number one position

Semiconductor industry revenue to increase 18% in 2024, Samsung regains number one position

Thanks to the rapid development of the artificial intelligence (AI) field, coupled with the huge demand for graphics cards (GPUs) and neural processing units (NPUs), the semiconductor industry has recorded impressive revenue growth.

List of Samsung Galaxy smartphones that will stop software support in 2025

List of Samsung Galaxy smartphones that will stop software support in 2025

Samsung is one of the smartphone manufacturers that offers the longest software support period for its devices, especially its flagships.

Which accounts are most targeted by hackers? How to protect them?

Which accounts are most targeted by hackers? How to protect them?

It probably won't surprise you to learn that Facebook, Instagram, and WhatsApp are top targets for hackers and scammers, but there are a few ways to protect your account.