Hacker News new | past | comments | ask | show | jobs | submit login

> In Go you have to "manually" defer a file.Close() call -- vs. the destructor getting automatically called in C++ (it even gets automatically called when a containing object is destructed, if it's a member, and so on). Go's version doesn't seem very "automatic" to me.

To clarify this one point, Go allows you to attach a destructor (finalizer) to an object, but since the language is garbage collected, there’s no guarantee of when the destructor will be called, if ever, since disabling the garbage collector is entirely possible, even if not advisable.

The File object will Close the file when the Finalizer runs, since the standard library attaches a finalizer to it, but you should defer the Close to deterministically ensure that the file is closed when you expect it to be closed, and to free that OS resource of a file handle as soon as possible, since some OSes limit how many you can have at a given time. Finalizers also won’t be run when the program exits, which is fine for most things, but you’ll want to have ensured any buffers were flushed before then, and defer can guarantee that.

Languages like Rust and C++ have deterministic destruction at the end of a given scope thanks to RAII, so it makes sense for them to lean more heavily on destructors there.

Java File*Stream objects should have “close()” called on them, from what I’m seeing on a Google search, so this doesn’t seem to be a surprising pattern for a garbage collected language. I know in Python you’re encouraged to use a “with” block to ensure that file objects get closed.

https://golang.org/pkg/runtime/#SetFinalizer




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: