1

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:

  1. How exactly is this happening? What is the value of c in closeUnlessNil(io.Closer)? I would have thought it's nil, but that's obviously not the case.
  2. Is it possible to write a generic closeUnlessNil(io.Closer) function that works with any io.Closer and calls Close() only if the parameter is not nil?
fstab
  • 992
  • 1
  • 11
  • 19

0 Answers0