Member-only story
Decrypt Go: runtime.SetFinalizer
Effective Usage and Common Pitfalls
If we want to do some resource release before an object is GC, we can use returns.SetFinalizer. It’s like executing defer to free resources before a function returns. For example:
List 1: Using runtime.SetFinalizer
type MyStruct struct {
Name string
Other *MyStruct
}
func main() {
x := MyStruct{Name: "X"}
runtime.SetFinalizer(&x, func(x *MyStruct) {
fmt.Printf("Finalizer for %s is called\n", x.Name)
})
runtime.GC()
time.Sleep(1 * time.Second)
runtime.GC()
}The official documentation explains that SetFinalizer associates a finalizer function with an object. When the garbage collector (GC) detects that an unreachable object has an associated finalizer, it will execute the finalizer and disassociate it. The object will be collected on the next GC cycle if it is unreachable and no longer has an associated finalizer.
Important Considerations
While runtime.SetFinalizer can be helpful, there are a few critical points to keep in mind:
- Deferred Execution: The
SetFinalizerfunction will not execute until the object is selected for garbage collection. Therefore, avoid usingSetFinalizerfor…

