The Go language is a new programming language that has added some unique syntax and features, among which defer and panic are two very important features. This article will introduce the relationship between defer and panic in Go language as well as their usage and characteristics.
Usage of defer
The defer statement in Go language is used to register a function. When the execution of this function ends or the current scope ends, the registered function will be automatically executed. defer can be used in multiple scenarios such as resource release, lock unlocking and error handling.
The following is an example of defer releasing resources:
func main() { file, err := os.Open("myfile.txt") // 在函数结束时,会自动关闭文件 defer file.Close() if err != nil { fmt.Println("Failed to open file.") return } // ... }
It is registered through the Close() function of the defer file, and the file will be automatically closed when the function execution ends.
The following is an example of unlocking a defer lock:
func main() { var lock sync.Mutex lock.Lock() // 当函数执行结束时,会自动解锁 defer lock.Unlock() // ... }
When the function execution ends, the Unlock() function will be automatically called to unlock the lock.
The execution order of defer is from back to front, which means that if multiple defer statements are registered, they will be executed in the reverse order. The following example will output Defer 2
, and then Defer 1
.
func main() { defer fmt.Println("Defer 1") defer fmt.Println("Defer 2") fmt.Println("Hello") }
Usage of panic
The panic keyword in Go language is used to throw an exception and terminate the execution of the current function or program. Panics will propagate up the function call stack until they are caught by the recover() function. If not caught, the entire program is exited and a call stack is printed.
In the following example code, when the length of the input string is less than 5, a panic will be triggered and the execution of the program will be terminated.
func hello(name string) { if len(name) < 5 { panic("Name is too short.") } fmt.Println("Hello", name) } func main() { hello("Tom") hello("Bob") hello("me") }
The output result is as follows:
Hello Tom Hello Bob panic: Name is too short. goroutine 1 [running]: main.hello(...) /Users/user/goland/src/main.go:4 main.main() /Users/user/goland/src/main.go:10 +0x81 exit status 2
Here we can see that when the input name is me
, panic will be triggered and program execution will be terminated.
The relationship between defer and panic
panic plays the role of immediately terminating program execution, which means that it can be triggered at any time, including before the end of function execution. In order to ensure that the program can release resources in time and perform some necessary cleanup work, the Go language introduces the defer mechanism, which allows the function to perform some cleanup operations before exiting.
When a panic is triggered in a function, it will exit immediately and execute all defer functions registered before the current function. The following example code manually triggers a panic and executes the defer function twice before exiting.
func main() { defer fmt.Println("Defer 1") defer fmt.Println("Defer 2") panic("Oops! Something went wrong.") }
The output results are as follows:
Defer 2 Defer 1 panic: Oops! Something went wrong. goroutine 1 [running]: main.main() /Users/user/goland/src/main.go:7 +0x81 exit status 2
We can see that after triggering the panic, the two defer functions are executed in reverse order.
In addition to registering the defer function at the end of the function, the Go language also allows multiple defer functions to be registered in the function. This means that if there are multiple defer functions in a function, even if one of the defer triggers a panic, the other defer functions can still be executed.
The following example code demonstrates that when a function registers multiple defer statements, one of the defer functions triggers a panic, but the other defer functions are still executed.
func init() { fmt.Println("Init 1") } func init() { fmt.Println("Init 2") } func main() { defer fmt.Println("Defer 1") defer func() { if err := recover(); err != nil { fmt.Println("Recovered:", err) } }() defer fmt.Println("Defer 2") panic("Oops! Something went wrong.") }
The output results are as follows:
Init 1 Init 2 Defer 2 Recovered: Oops! Something went wrong. Defer 1
We can see that the function first executes two init functions, and then executes three defer functions in sequence. When one of the defers triggers a panic, but is caught by another defer and the program is resumed, eventually both defer functions execute normally.
In actual development, defer and panic are often used in pairs. defer is used to release resources and perform cleanup operations, and panic is used to handle exceptions. When a function needs to perform multiple cleanup operations before exiting, we can use a defer wrapper function at the beginning of the function and use the recover() function to prevent the function from exiting early. This way of writing is very common and provides a strong guarantee for us to write robust programs.
The above is the detailed content of What is the relationship between defer and panic in Go language?. For more information, please follow other related articles on the PHP Chinese website!

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

删除字符串的方法:1、用TrimSpace()来去除字符串空格;2、用Trim()、TrimLeft()、TrimRight()、TrimPrefix()或TrimSuffix()来去除字符串中全部、左边或右边指定字符串;3、用TrimFunc()、TrimLeftFunc()或TrimRightFunc()来去除全部、左边或右边指定规则字符串。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.
