Deferred calls to defer in go

Source: Internet
Author: User
// code_006_defer_usage project main.gopackage mainimport ( "fmt")func test(x int) { fmt.Println(100 / x)}func main() { //关键字 defer ?于延迟一个函数或者方法(或者当前所创建的匿名函数)的执行。 //注意,defer语句只能出现在函数或方法的内部。 fmt.Println("this is a test") defer fmt.Println("this is a defer") //defer语句经常被用于处理成对的操作,如打开、关闭、连接、断开连接、加锁、释放锁。 //通过defer机制,不论函数逻辑多复杂,都能保证在任何执行路径下,资源被释放。 //释放资源的defer应该直接跟在请求资源的语句后。 //如果一个函数中有多个defer语句,它们会以LIFO(后进先出)的顺序执行。 //哪怕函数或某个延迟调用发生错误,这些调用依旧会被执?。 defer fmt.Println("aaaa") defer fmt.Println("bbbb") defer test(0) defer fmt.Println("ccc") a, b := 10, 20 defer func(x int) { fmt.Println("\ndefer:", x, b) //b闭包引用 }(a) a += 10 b += 100 fmt.Printf("a= %d, b= %d", a, b)}

Deferred calls to defer in go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.