Skip to content

Instantly share code, notes, and snippets.

@deltamobile
Last active January 8, 2024 18:19
Show Gist options
  • Save deltamobile/6511901 to your computer and use it in GitHub Desktop.
Save deltamobile/6511901 to your computer and use it in GitHub Desktop.
An example of the use of a finalizer (the runtime.SetFinalizer function) for a Go (golang) data structure. The documentation describes the expected signature for the function passed to SetFinalizer, but it is nice to see a running example. Tested with Go 1.1.2.
package main
import (
"fmt"
"runtime"
"time"
)
type Foo struct {
name string
num int
}
func finalizer(f *Foo) {
fmt.Println("a finalizer has run for ", f.name, f.num)
}
var counter int
func MakeFoo(name string) (a_foo *Foo) {
a_foo = &Foo{name, counter}
counter++
runtime.SetFinalizer(a_foo, finalizer)
return
}
func Bar() {
f1 := MakeFoo("one")
f2 := MakeFoo("two")
fmt.Println("f1 is: ", f1.name)
fmt.Println("f2 is: ", f2.name)
}
func main() {
for i := 0; i < 3; i++ {
Bar()
time.Sleep(time.Second)
runtime.GC()
}
fmt.Println("done.")
}
@GrimTheReaper
Copy link

You should link play.golang.org
http://play.golang.org/p/jWhRSPNvxJ

something like:
[play](http://play.golang.org/p/jWhRSPNvxJ) with this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment