why is example Go code waiting until after checking the error to `defer file.Close()`? the way i see it, if there's a statement that says "close the file when the current function goes out of scope", you best believe i'm slapping that as soon as physically possible after opening the file

@kinsey If os.Open (or os.Create) returns an error then the file pointer returned will be nil. So defer file.Close() would be... not ok.. wait? No, you can call Close() on a nil *os.File!

TIL

@quirk actually, i checked the source code, and you can call Close() on a nil *os.File, but it gives an error. and if there's an error opening the file you won't have an opened file to close anyway, so i thought of a better Standard Thing To Do maybe

inputFile, err := os.Open("/path/to/file")
if err == nil {
defer inputFile.Close()
} else {
// handle error...
}

Follow

@kinsey I'll return an error, yea, but you can just ignore the return value in that case.

@quirk yeah, i was about to say, i guess it's not super essential to do anything with that error, but it still feels nicer because it avoids executing code that we know is going to basically do Nothing

@kinsey It's also kind of a go idiom what nil values *should* be valid if possible.

So, I guess that while a nil *os.File is not a valid open file its a "valid" *os.File, in the sense that you can call all the methods and expect to get an error in return instead of panicking. 🤷‍♀️

Sign in to participate in the conversation
Computer Fairies

Computer Fairies is a Mastodon instance that aims to be as queer, friendly and furry as possible. We welcome all kinds of computer fairies!