Clean up what the GC can't clean up
Gophers coming from OOP languages may occasionally miss a finalizer in Go. Fret no more: With the AddCleanup function, new in Go 1.24, you can close files, disconnect DB connections, and clean up other resources once the object containing these resources becomes unreachable.
Here is how it works:
If the object containing the resource becomes unreachable, hence due for garbage collection, the cleanup function is called.
A small but important caveat: The cleanup function must not refer to the object containing the resources. Otherwise, the object would always be referenced by reachable code and would never become subject to garbage collection; hence, the cleanup function would never run.
The example in the screenshot and in the playground is simplified as much as possible. The object is a temporary file, and the cleanup function removes the file from disk.
https://go.dev/play/p/05BWkHUHWZo?v=gotip
=> More informations about this toot | View the thread | More toots from christophberger@c.im
text/gemini
This content has been proxied by September (3851b).