Toot

Written by Christoph Berger on 2025-01-15 at 15:22

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

=> View attached media

=> More informations about this toot | View the thread | More toots from christophberger@c.im

Mentions

Tags

Proxy Information
Original URL
gemini://mastogem.picasoft.net/toot/113833053194107075
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
223.005198 milliseconds
Gemini-to-HTML Time
1.348906 milliseconds

This content has been proxied by September (3851b).