Use runtime.SetFinalizer to attach a cleanup function to a Go object that the garbage collector will run when the object becomes unreachable. This is essential for releasing resources allocated outside Go's memory management, such as C library handles.
import "runtime"
type Resource struct {
handle uintptr
}
func (r *Resource) cleanup() {
// Release external resource, e.g., C.free(r.handle)
}
func NewResource() *Resource {
r := &Resource{handle: allocateExternalResource()}
runtime.SetFinalizer(r, (*Resource).cleanup)
return r
}