search
HomeBackend DevelopmentGolangGolang function defer statement usage analysis

Golang is an object-oriented programming language that supports concurrency and is compiled into machine code. It has simple syntax, efficient performance and a rich standard library. In Golang, the defer statement is used to delay execution of a function. This language feature is very useful when writing code. This article will explain the use and analysis of the defer statement of Golang functions.

1. Basic syntax of defer statement

In Golang, the defer statement can be used to postpone the execution of a function or method until the function returns. The syntax of the defer statement is very simple. The syntax format is:

defer 函数名(参数列表)

where defer is a keyword in the Golang language. The defer statement can be used anywhere, but it is best to declare it at the beginning of the function or method, so that the execution process of the function or method can be displayed more clearly.

2. Execution principle of defer statement

When executing a function, if there are defer statements inside the function, then these defer statements will be executed in reverse order according to the order of definition, that is to say, they are defined last The defer statement is executed first, and the defer statement defined first is executed last. The defer statement has last-in-first-out logic.

For example, the following code implements a simple defer statement example:

package main

import (
    "fmt"
)

func main() {
    defer fmt.Println("defer 1")
    defer fmt.Println("defer 2")
    defer fmt.Println("defer 3")

    fmt.Println("Hello, Golang!")
}

The output result is:

Hello, Golang!
defer 3
defer 2
defer 1

As you can see, fmt.Println("Hello , Golang!"), and then executed three defer statements based on the last-in-first-out logic.

3. Application scenarios of defer statement

The defer statement is very commonly used in Golang language and can be used in the following scenarios:

  1. Close the file

When using Golang to operate files, you need to close the file immediately after the file opening operation is completed. If you use the Close() function directly, the file may not be closed when an unexpected situation occurs when the program is running. At this time, you can Use the defer statement to delay the execution of the Close() function until the end of the function to ensure that the file can be closed normally. The following is a relevant code example:

file, err := os.Open("test.txt")
if err != nil {
    fmt.Println(err)
}
defer file.Close()
  1. Unlocking operation

In Golang, use sync.Mutex to control the mutex lock and release the lock at the end of the function. You can use the defer statement to avoid deadlock in the program. The following is a sample code:

var mutex sync.Mutex

func sample() {
    mutex.Lock()
    defer mutex.Unlock()

    // 操作代码
}
  1. Calculate function execution time

When testing the performance of a Golang function, you can record the time before and after the function is executed, and calculate the time difference to obtain the execution time of the function. If the time is calculated directly inside the function, the timestamp may be obtained in different places due to a lot of code logic, making debugging complicated. At this time, you can use the defer statement to calculate the time difference at the end of the function to obtain the function execution time.

import (
    "time"
)

func calcExecTime() {
    startTime := time.Now().UnixNano()
    defer func() {
        fmt.Println("time", float32(time.Now().UnixNano()-startTime)/1000000.0)
    }()

    // 操作代码
}

4. Precautions for the defer statement

When using the defer statement, you need to pay attention to the following points:

  1. The execution of the defer statement will be in the current function or It is executed before the method exits, so any code in the function or method that modifies the internal state of the function or method will still take effect when defer is executed.
  2. The defer statement is usually used to clean up some resources, such as closing files or releasing memory, so be sure to use the defer statement at the right time.
  3. When using the defer statement, you should avoid using functions containing expensive code, such as large loops or connecting to the database, which may affect the performance of the program.

5. Summary

In Golang, the defer statement can be used to postpone the execution of a function or method until the function returns. The defer statement is very commonly used in the Golang language and can be used in closing files, unlocking operations, and calculating function execution time. When using the defer statement, you should avoid using functions containing expensive code to prevent affecting the performance of the program.

The above is the detailed content of Golang function defer statement usage analysis. 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
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

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 Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment