Golang Foundation--elaborate defer

Source: Internet
Author: User

Defer anonymous function properties

  • Execution is similar to destructors in other languages, followed by the execution of the function body in the order of invocation 相反顺序

    //执行顺序相反package mainimport "fmt"func main() {    fmt.Println("a")    defer fmt.Println("b")    defer fmt.Println("c")}/*输出acb*/
  • Even if a function occurs 严重的错误 , it is similar to try...except
  • Often used for resource cleanup, file closing, unlocking, and recording time

  • Calls that support anonymous functions
  • You can modify the result of a function calculation after return by using the anonymous function mate
    -If a variable in the function body is a parameter of an anonymous function when defer, the copy is obtained when the defer is defined, otherwise the address of a variable is referenced

    //支持匿名函数package mainimport "fmt"func main() {    for i := 0; i < 3; i++ {        defer func() { //函数体内的变量传递到defer匿名函数            fmt.Println(i) //此时引用的时变量i的地址        }()    }}/*输出333*/
  • Go has no exception mechanism, but has panic/recover mode to handle errors
  • Panic can be triggered from anywhere

    Panic error mechanism

    //panic 错误机制,遇到panic语句后,后面不会再执行package mainimport "fmt"func main() {    A()    B()    C()}func A() {    fmt.Println("func a")}func B() {    panic("Panic B")}func C() {    fmt.Println("func")}/*输出A()-->  func aB()---> panic: Panic B---------------    goroutine 1 [running]:    main.B()C()     C:/Users/faily/Desktop/workspace/src/defer1.go:17 +0x40    main.main()        C:/Users/faily/Desktop/workspace/src/defer1.go:8 +0x2c    exit status 2    exit status 1*/
  • Defer, with recover and anonymous function handlers, a critical error (panic statement), a program error, continues execution, similar to the Python language, the try...except finally statement.

    //defer,recover机制,处理panic引发的机制package mainimport "fmt"func main() {    A()    B()    C()}func A() {    fmt.Println("func a")}func B() {    defer func() {                          //defer函数放在panic之前        if err := recover(); err != nil {   //注册recover函数(判断是否触发panic错误),并判断            fmt.Println("Recover in B")     //如果程序出现panic,并且err不为nil(真实存在)        }     }()                                     //记住,defer的匿名函数大括号后要加上()                                    panic("Panic B")                        //跳过程序错误,继续后面的执行。}func C() {    fmt.Println("func C")}/*输出A()-->  func aB()-->  Recover in BC()-->  

    ~ ~ Leave a question, interested in a small partner welcome to answer

    Run the following code and parse the output

      package Mainimport "FMT" Func Main () {var fs = [4]func () {}//define a variable FS, type is an array, the type of the array element is funcfor I: = 0 ; I < 4; i++ {defer FMT. Println ("Defer i=", i) defer func () {fmt. PRINTLN ("Defer closure i=", I)} () Fs[i] = func () {fmt. Println ("Closure i=", i)}}for _, F: = Range fs {f ()}}  
Related Article

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.