Closed johncming closed 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) }
defer
被调用几次?