runtime.SetFinalizer.
runtime.SetFinalizer lets you register a function that runs when the garbage collector finds an object is no longer used.
Starting with Go 1.24, you should use runtime.AddCleanup instead, as it is safer and less likely to cause errors.
Refer to the documentation of runtime.SetFinalizer and runtime.AddCleanup for more information.