search
HomeBackend DevelopmentGolangWhat is the delayed execution statement in Go language

What is the delayed execution statement in Go language

Jan 11, 2023 pm 06:28 PM
golanggo languagedefer

In the Go language, the delayed execution statement is the defer statement, and the syntax is "defer any statement". The defer statement will delay processing of the statements that follow it. When the function to which the defer belongs is about to return, the delayed statements will be executed in the reverse order of defer; that is, the statement that is deferred first will be executed last, and the statement that is defer last will be executed. statement is executed first.

What is the delayed execution statement in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Delayed execution statement (defer statement) in Go language

There is a delayed execution statement in Go language, which is controlled by the defer keyword logo.

The defer keyword will delay processing of the statements following it. When the function to which defer belongs is about to return, the delayed processing statements will be executed in the reverse order of defer, that is, the statement that is defer first The statement that is executed last and the last defer statement is executed first.

The format is as follows:

defer 任意语句

The statements after defer will not be executed immediately. When the function to which defer belongs is about to return, all defer statements in the function body will be reversed in the order of appearance. Execution, that is, the last defer statement in the function body is executed first.

package main

import "fmt"

func main(){
	fmt.Println("start now")
	defer fmt.Println("这是第一句defer语句")
	defer fmt.Println("这是第二句defer语句")
	defer fmt.Println("这是第三句defer语句")
	fmt.Println("end")
}

The execution results are as follows:

start now
end
这是第三句defer语句
这是第二句defer语句
这是第一句defer语句

Since the defer statement is called when the current function is about to return, defer is often used to release resources.

The processing order of multiple delayed execution statements

When multiple defer behaviors are registered, they will be executed in reverse order (similar to a stack, that is, last in, first out) , the following code delays processing of a series of numerical print statements in order, as shown below:

package main
import (
    "fmt"
)
func main() {
    fmt.Println("defer begin")
    // 将defer放入延迟调用栈
    defer fmt.Println(1)
    defer fmt.Println(2)
    // 最后一个放入, 位于栈顶, 最先调用
    defer fmt.Println(3)
    fmt.Println("defer end")
}

The code output is as follows:

defer begin
defer end
3
2
1

The result analysis is as follows:

  • The delay order of the code is reversed from the final execution order.

  • Delayed calling is done when the function where defer is located ends. The end of the function can be when it returns normally or when a downtime occurs.

Use delayed execution statements to release resources when the function exits

It is cumbersome to deal with paired operations in business or logic Things like opening and closing files, receiving and replying to requests, locking and unlocking, etc. Among these operations, the most easily overlooked is the correct release and closing of resources at each function exit.

The defer statement is exactly the statement that is executed when the function exits, so using defer can handle resource release issues very conveniently.

1) Use delayed concurrent unlocking

In the following example, map will be used concurrently in the function. To prevent race conditions, sync.Mutex is used for locking. See the following code:

var (
    // 一个演示用的映射
    valueByKey      = make(map[string]int)
    // 保证使用映射时的并发安全的互斥锁
    valueByKeyGuard sync.Mutex
)
// 根据键读取值
func readValue(key string) int {
    // 对共享资源加锁
    valueByKeyGuard.Lock()
    // 取值
    v := valueByKey[key]
    // 对共享资源解锁
    valueByKeyGuard.Unlock()
    // 返回值
    return v
}

The code description is as follows:

  • Line 3 instantiates a map, the key is string type and the value is int.

  • Line 5, map is not concurrency safe by default, prepare a sync.Mutex mutex to protect map access.

  • Line 9, the readValue() function gives a key and returns the value after getting the value from the map. This function will be used in a concurrent environment and needs to ensure concurrency safety.

  • Line 11, use mutex to lock.

  • Line 13, get the value from map.

  • Line 15, use the mutex to unlock.

  • Line 17 returns the obtained map value.

Use the defer statement to simplify the above statement, refer to the code below.

func readValue(key string) int {
    valueByKeyGuard.Lock()
   
    // defer后面的语句不会马上调用, 而是延迟到函数结束时调用
    defer valueByKeyGuard.Unlock()
    return valueByKey[key]
}

Lines 6~8 of the above code are modifications and additions to the previous code. The code description is as follows:

  • Line 6 is in the mutex After locking, use the defer statement to add an unlock. This statement will not be executed immediately, but will be executed when the readValue() function returns.

  • Line 8, the process of querying the value from the map and returning it is the same as the way of writing without using a mutex. Compared with the above code, this way of writing is simpler.

2) Using delayed release of file handle

The operation of a file requires several processes: opening the file, obtaining and operating file resources, and closing the resources. If after the operation is completed, If the file resource is not closed, the process will never be able to release the file resource. In the following example, a function to obtain the file size based on the file name will be implemented. The function requires operations such as opening the file, obtaining the file size, and closing the file. Since each system operation requires Error handling is required, and each step of processing will cause a possible exit, so resources need to be released when exiting, and we need to pay close attention to correctly releasing file resources at the function exit, refer to the following code:

// 根据文件名查询其大小
func fileSize(filename string) int64 {
    // 根据文件名打开文件, 返回文件句柄和错误
    f, err := os.Open(filename)
    // 如果打开时发生错误, 返回文件大小为0
    if err != nil {
        return 0
    }
    // 取文件状态信息
    info, err := f.Stat()
   
    // 如果获取信息时发生错误, 关闭文件并返回文件大小为0
    if err != nil {
        f.Close()
        return 0
    }
    // 取文件大小
    size := info.Size()
    // 关闭文件
    f.Close()
   
    // 返回文件大小
    return size
}

The code description is as follows:

  • Line 2 defines the function to obtain the file size, and the return value is the 64-bit file size value.

  • Line 5, use the function Open() provided by the os package to open a file based on the given file name, and return the handle used to operate the file and the operation error.

  • Line 8, if an error occurs during the opening process, such as the file is not found, the file is occupied, etc., the file size will be returned as 0.

  • 第 13 行,此时文件句柄 f 可以正常使用,使用 f 的方法 Stat() 来获取文件的信息,获取信息时,可能也会发生错误。

  • 第 16~19 行对错误进行处理,此时文件是正常打开的,为了释放资源,必须要调用 f 的 Close() 方法来关闭文件,否则会发生资源泄露。

  • 第 22 行,获取文件大小。

  • 第 25 行,关闭文件、释放资源。

  • 第 28 行,返回获取到的文件大小。

在上面的例子中,第 25 行是对文件的关闭操作,下面使用 defer 对代码进行简化,代码如下:

func fileSize(filename string) int64 {
    f, err := os.Open(filename)
    if err != nil {
        return 0
    }
    // 延迟调用Close, 此时Close不会被调用
    defer f.Close()
    info, err := f.Stat()
    if err != nil {
        // defer机制触发, 调用Close关闭文件
        return 0
    }
    size := info.Size()
    // defer机制触发, 调用Close关闭文件
    return size
}

代码中加粗部分为对比前面代码而修改的部分,代码说明如下:

  • 第 10 行,在文件正常打开后,使用 defer,将 f.Close() 延迟调用,注意,不能将这一句代码放在第 4 行空行处,一旦文件打开错误,f 将为空,在延迟语句触发时,将触发宕机错误。

  • 第 16 行和第 22 行,defer 后的语句(f.Close())将会在函数返回前被调用,自动释放资源。

【相关推荐:Go视频教程编程教学

The above is the detailed content of What is the delayed execution statement in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Security Considerations When Developing with GoSecurity Considerations When Developing with GoApr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Understanding Go's error InterfaceUnderstanding Go's error InterfaceApr 27, 2025 am 12:16 AM

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

Error Handling in Concurrent Go ProgramsError Handling in Concurrent Go ProgramsApr 27, 2025 am 12:13 AM

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher

How do you implement interfaces in Go?How do you implement interfaces in Go?Apr 27, 2025 am 12:09 AM

In Go language, the implementation of the interface is performed implicitly. 1) Implicit implementation: As long as the type contains all methods defined by the interface, the interface will be automatically satisfied. 2) Empty interface: All types of interface{} types are implemented, and moderate use can avoid type safety problems. 3) Interface isolation: Design a small but focused interface to improve the maintainability and reusability of the code. 4) Test: The interface helps to unit test by mocking dependencies. 5) Error handling: The error can be handled uniformly through the interface.

Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Apr 27, 2025 am 12:06 AM

Go'sinterfacesareimplicitlyimplemented,unlikeJavaandC#whichrequireexplicitimplementation.1)InGo,anytypewiththerequiredmethodsautomaticallyimplementsaninterface,promotingsimplicityandflexibility.2)JavaandC#demandexplicitinterfacedeclarations,offeringc

init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.