Standard library / runtime

runtime.SetFinalizer()

Register or clear a finalizer on a suitable object. Never depend on its timing for cleanup; use explicit Close. This example registers and clears without testing invocation. Expected stdout: 'cleared\n'.

Formal Syntax & Structure

go syntaxgo
func SetFinalizer(obj any, finalizer any)

Parameters & Attributes

NameTypeDescription
objanyPointer to a suitable heap object whose finalizer is configured.
finalizeranyFunction accepting the object, or nil to clear its finalizer.

Working Example

Example Snippetgo
package main
import (  "fmt"  "runtime")
func main() {  type Resource struct{ data [64]byte }  p := new(Resource)  runtime.SetFinalizer(p, func(r *Resource) {})  runtime.SetFinalizer(p, nil)  runtime.KeepAlive(p)  fmt.Println("cleared")}
Go Reference