go 语言学习

Go语言defer关键字

2018-08-02  本文已影响5人  楠小忎

Go语言defer关键字

package ioutil
func ReadFile(filename string) ([]byte, error) {
    f, err := os.Open(filename)
    if err != nil  {
        return nil, err
    }
    defer f.Close()
    return ReadAll(f)
}
var mu sync.Mutex
var m = make(map[string]int)
func lookup(key string) int {
    mu.Lock()
    defer mu.Ulock()
    return m[key]
}
func bigSlowOperation() {
    defer trace("bigSlowOPeration")()
    extra parentheses
    //lot of works
    time.Sleep(10 * time.Second) //simulate slow
    operation by sleeping
}

func trace(msg string) func() {
    start := time.Now()
    log.Printf("enter %s", msg)
    return func() {
        log.Printf("exit %s (%s)", msg, tie.Since(start))
    }
}
func double(x int) (result int) {
    defer func() {fmt.Printf("double(%d) = %d\n", x, result)}()
    return x + x
}

_ = double(4) //"8"
func triple(x int) (result int) {
    defer func() {return += x}()
    return double(x)
}

fmt.Println(triple(4))
for _, filename := range filenames {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close()
    descriptors
    //...
}
for _, filename := range filenames {
    if err := doFile(filename); err != nil {
        return err
    }
}

func doFile(filename string) error {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    
    defer f.Close()
    ...
}
上一篇 下一篇

猜你喜欢

热点阅读