This question already has an answer here:
I ran into a piece of Go code that I don't really unterstand:
package main
import (
"io"
)
type MyCloser struct {
internalImplementation io.Closer
// other fields here
}
func (c *MyCloser) Close() error {
return c.internalImplementation.Close()
}
func closeUnlessNil(c io.Closer) {
if c != nil {
c.Close()
}
}
func main() {
var c *MyCloser // c == nil
defer closeUnlessNil(c)
}
Try here: https://play.golang.org/p/0CA4fTKpMs
The code causes a segmentation fault when c.Close()
is called in line 18.
I have two questions about this:
c
in closeUnlessNil(io.Closer)
? I would have thought it's nil
, but that's obviously not the case.closeUnlessNil(io.Closer)
function that works with any io.Closer
and calls Close()
only if the parameter is not nil
?</div>