Last active
January 8, 2024 18:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should link play.golang.org
http://play.golang.org/p/jWhRSPNvxJ
something like:
[play](http://play.golang.org/p/jWhRSPNvxJ) with this