johncming / go-spec

my wiki
Apache License 2.0
0 stars 0 forks source link

defer被调用几次? #118

Closed johncming closed 5 years ago

johncming commented 5 years ago

defer被调用几次?

package call_defer

import (
    "errors"
    "fmt"
    "testing"
)

var ops []string

type instance struct {
    index int
}

func NewInstance() (*instance, error) {
    var err error
    i := &instance{}
    if i.index%2 != 0 {
        err = errors.New("haha error")
    }
    return i, err
}

func (i *instance) Close() {
    ops = append(ops, "closed")
}

func callme() (*instance, error) {
    for i := 0; i < 5; i++ {
        i, err := NewInstance()
        if err != nil {
            return nil, err
        }
        defer i.Close()
    }

    return nil, nil
}

func Test(t *testing.T) {
    callme()
    fmt.Printf("%+v\n", ops)
}