Go——延迟函数 defer 用法举例 (转)

转自: https://www.cnblogs.com/zhangmingcheng/p/15205970.html

例一、defer_a.go

package main
import "fmt"
func main() {
    fmt.Println("a return:", a()) // 打印结果为 a return: 0
}
 
func a() int {
    var i int
    defer func() {
        i++
        fmt.Println("a defer2:", i) // 打印结果为 a defer2: 2
    }()
    defer func() {
        i++
        fmt.Println("a defer1:", i) // 打印结果为 a defer1: 1
    }()
    return i
}

// go run  defer_a.go
// a defer1: 1
// a defer2: 2
// a return: 0

 

例二、defer_b.go

package main
import "fmt"
func main() {
    fmt.Println("b return:", b()) // 打印结果为 b return: 2
}
func b() (i int) {
    defer func() {
        i++
        fmt.Println("b defer2:", i) // 打印结果为 b defer2: 2
    }()
    defer func() {
        i++
        fmt.Println("b defer1:", i) // 打印结果为 b defer1: 1
    }()
    return i // 或者直接 return 效果相同
}

// go run  defer_b.go
// b defer1: 1
// b defer2: 2
// b return: 2

 

例三、defer_c.go

package main
import "fmt"
func main() {
    c:=c()
    fmt.Println("c return:", *c, c) // 打印结果为 c return: 2 0xc082008340
}
func c() *int {
    var i int
    defer func() {
        i++
        fmt.Println("c defer2:", i, &i) // 打印结果为 c defer2: 2 0xc082008340
    }()
    defer func() {
        i++
        fmt.Println("c defer1:", i, &i) // 打印结果为 c defer1: 1 0xc082008340
    }()
    return &i
}

// go run  defer_c.go
// c defer1: 1 0xc0000b2008
// c defer2: 2 0xc0000b2008
// c return: 2 0xc0000b2008

 

例四、defer_d.go

package main
import (
    "fmt"
    "time"
)
func main() {
    defer P(time.Now())
    time.Sleep(5e9)   //5 seconds
    fmt.Println("main ", time.Now())
}
 
func P(t time.Time) {
    fmt.Println("defer", t)
    fmt.Println("P    ", time.Now())
}

// go run  defer_d.go
// main  2022-01-26 17:10:00.461692 +0800 CST m=+5.000733360
// defer 2022-01-26 17:09:55.460852 +0800 CST m=+0.000079331
// P     2022-01-26 17:10:00.462076 +0800 CST m=+5.001117721

 

例五、defer_e.go

package main
import (
    "errors"
    "fmt"
    "time"
    // "os"
)
func main() {
    e := errors.New("error")
    fmt.Println(e)
    // (3)panic(e) // defer 不会执行
    // (4)os.Exit(1) // defer 不会执行
    defer fmt.Println("defer")
    // (1)go func() { panic(e) }() // 会导致 defer 不会执行
    // (2)panic(e) // defer 会执行
    time.Sleep(1e9)
    fmt.Println("over.")
    // (5)os.Exit(1) // defer 不会执行
}
// go run  defer_e.go
// error
// over.
// defer

 

例六、defer_f.go

package main
import "fmt"
func main() {
    defer fmt.Println()
    defer fmt.Print(1)
    defer fmt.Print(2)
    defer fmt.Print(3)
    defer fmt.Print(4)
}
// go run  defer_f.go
// 4321

 

posted @ 2022-01-26 17:14  会飞的斧头  阅读(79)  评论(0编辑  收藏  举报