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:
- How exactly is this happening? What is the value of
c
incloseUnlessNil(io.Closer)
? I would have thought it'snil
, but that's obviously not the case. - Is it possible to write a generic
closeUnlessNil(io.Closer)
function that works with anyio.Closer
and callsClose()
only if the parameter is notnil
?