Go language's defer is considered a new feature of the language, at least compared to today's mainstream programming languages.
The defer statement calls a function. The execution of this function will be postponed until the peripheral function returns, or the peripheral function runs to the end, or the corresponding goroutine panics
Whenever defer is executed, it The subsequent function value (in Go, the function is a reference type, a first-class citizen, and can be assigned to a variable) and function parameters will be evaluated, but the function will not be called immediately until (↑) the above three situations occur. This is the whole content of defer, gone, the rest is the best practice of defer
The function will not be called immediately
Start with the simplest one:
func readFile(fileName string){ f,err := os.Open(fileName) if err!=nil { return } defer f.Close() var content [1024]byte f.Read(content[:]) fmt.Printf("%s",content) } func main() { readFile("test.data") }
The program outputs the first 1024 bytes of test.data. It is worth mentioning that open/close pairing operations like this are the idiomatic usage of defer. This example explains the second half of the above sentence
"But the function will not be called"
Because if f.Close() after defer is not delayed, then the file descriptor If they are all closed, nothing will be read.
The function value and function parameters are evaluated, but the function is not called immediately
The following example will explain the first half, it comes from , slightly Modification:
func trace(funcName string) func(){ start := time.Now() fmt.Printf("function %s enter\n",funcName) return func(){ log.Printf("function %s exit (elapsed %s)",funcName,time.Since(start)) } } func foo(){ defer trace("foo()")() time.Sleep(5*time.Second) } func main(){ foo() foo() } /* OUTPUT: function foo() enter function foo() exit (elapsed 5.0095471s) function foo() enter function foo() exit (elapsed 5.0005382s) */
Why does foo output enter and then wait for about five seconds before outputting exit? Because as we said, the function value and parameters after
defer will be evaluated but the actual function The call has to wait until the end
The function value here is the anonymous function returned by trace(). The function parameter is of course the string literal value "foo()". The evaluation of trace("foo()") will Output function foo() enter, the actual function call trace("foo()")(), that is, the output function foo() exit(elapsed x.x) will be postponed until return execution (if return will update the return value variable, it will be executed after the update before executing the defer function).
Miscellaneous
To say a little more, if there are multiple defer statements, the execution order of the last defer function is opposite to the order in which defer appears, such as:
func main() { func1 := func(){ fmt.Println("func1() execution deferred") } func2 := func(){ fmt.Println("func2() execution deferred") } defer func1() defer func2() fmt.Println("strat\nworking...") } /* OUTPUT: strat working... func2() execution deferred func1() execution deferred */
The above is the detailed content of Introduction to go defer (go delay function). For more information, please follow other related articles on the PHP Chinese website!

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

本篇文章带大家了解一下golang 的几种常用的基本数据类型,如整型,浮点型,字符,字符串,布尔型等,并介绍了一些常用的类型转换操作。

闭包(closure)是一个函数以及其捆绑的周边环境状态(lexical environment,词法环境)的引用的组合。 换而言之,闭包让开发者可以从内部函数访问外部函数的作用域。 闭包会随着函数的创建而被同时创建。

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 自带的 HttpClient 的超时机制,希望对大家有所帮助。


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
