init: v1.0.0
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
// Package final call the finalizer befor an object destruction.
|
||||
// Clear the memeory, recode logs or something else.
|
||||
// Example:
|
||||
// Define an type
|
||||
// type Obj struct {
|
||||
// // ...
|
||||
// }
|
||||
//
|
||||
// func NewObj() *Obj {
|
||||
// a := &obj{}
|
||||
// final.SetFinalizer(a)
|
||||
// return a
|
||||
// }
|
||||
//
|
||||
// func (o *Obj) Final() {
|
||||
// // do stuffs
|
||||
// }
|
||||
package final
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// Finalizerable clear a object befor destruction
|
||||
type Finalizerable interface {
|
||||
Finalizer()
|
||||
}
|
||||
|
||||
// SetFinalizer set obj to runtime with Finalizerable,
|
||||
// if obj implements Finalizerable interface, then call it befor obj
|
||||
// destruction, or do nothing
|
||||
func SetFinalizer(obj interface{}) {
|
||||
runtime.SetFinalizer(obj, doFinal)
|
||||
}
|
||||
|
||||
// ClearFinalizer clear all finalizer on obj
|
||||
func ClearFinalizer(obj interface{}) {
|
||||
runtime.SetFinalizer(obj, nil)
|
||||
}
|
||||
|
||||
func doFinal(obj interface{}) {
|
||||
if f, ok := obj.(Finalizerable); ok {
|
||||
f.Finalizer()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package final
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type A struct {
|
||||
tag string
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func NewA(tag string, t *testing.T) *A {
|
||||
t.Log(tag, "init")
|
||||
a := &A{tag: tag, t: t}
|
||||
SetFinalizer(a)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *A) Finalizer() {
|
||||
a.t.Log(a.tag, "final")
|
||||
}
|
||||
|
||||
func function(t *testing.T) {
|
||||
a := NewA("a in function", t)
|
||||
_ = a
|
||||
}
|
||||
|
||||
// $ go test -run=TestFinal -v
|
||||
// === RUN TestFinal
|
||||
// TestFinal: final_test.go:15: a init
|
||||
// TestFinal: final_test.go:15: a in function init
|
||||
// TestFinal: final_test.go:22: a in function final
|
||||
// TestFinal: final_test.go:22: a final
|
||||
// --- PASS: TestFinal (1.00s)
|
||||
// PASS
|
||||
func TestFinal(t *testing.T) {
|
||||
a := NewA("a", t)
|
||||
function(t)
|
||||
_ = a
|
||||
runtime.GC()
|
||||
time.Sleep(1 * time.Second)
|
||||
runtime.GC()
|
||||
}
|
||||
Reference in New Issue
Block a user