You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Excuse me, but I have an impression that you haven't seen the full example at all. I'm not talking about calling methods on nil non-interface values here at all. I'll try to explain in here then.
Let's assume that type *A implements io.Closer. I have a function maybeClose implemented as follows:
a := &A{}
defer func() { maybeClose(a) }()
if err := someValidation(a); err != nil { return nil, err }
if err := someMoreChecks(a); err != nil { return nil, err }
...
if err := lastCheck(a); err != nil { return nil, err }
// alright, a is valid, let's not close it, but return it instead
b := a
a = nil
return b, nil
If all validations passed, I assign the object to other variable and nil the a variable. The deferred action is run, takes an a variable, which is nil at this point. Somehow c != nil in maybeCheck function does not catch it and happily calls Close on it, which might end in nil dereference if Close accesses some fields in *A.
Now, either change c io.Closer in maybeClose to c *A or change a := &A{} to a := func() io.Closer { return &A{} } () and it works - Close is not invoked anymore in deferred function.
go version go1.5.1 linux/amd64
There is an example code in http://play.golang.org/p/5ZpPG0hhqJ
And here is a truncated code to the essence: http://play.golang.org/p/W1lmCPoc7D
I expected the nil check in
maybeClose
to prevent executing Close, but apparently it is executed on a nil variable.The text was updated successfully, but these errors were encountered: