在面向对象的语言中,我使用类变量来跟踪当前生成的实例数量,方法是在构建时递增和在销毁时递减。
我尝试在 go 中实现类似的行为:
package entity
type Entity struct {
Name string
}
func New(name string) Entity {
entity := Entity{name}
counter++
return entity
}
var counter int = 0
func (e *Entity) Count() int {
return counter
}
因为我不能通过析构函数递减计数器,所以它只工作了一半。
我能以某种方式模仿对象破坏吗? 我将如何正确跟踪实例计数?
最佳答案
您可以使用 runtime.SetFinalizer像这样。参见 here Playground 版本。
package main
import (
"fmt"
"runtime"
)
type Entity struct {
Name string
}
var counter int = 0
func New(name string) Entity {
entity := Entity{name}
counter++
runtime.SetFinalizer(&entity, func(_ *Entity) {
counter--
})
return entity
}
func (e *Entity) Count() int {
return counter
}
func main() {
e := New("Sausage")
fmt.Println("Entities", counter, e)
e = New("Potato")
fmt.Println("Entities", counter, e)
runtime.GC()
fmt.Println("Entities", counter)
e = New("Leek")
fmt.Println("Entities", counter)
runtime.GC()
fmt.Println("Entities", counter)
}
这打印
Entities 1 {Sausage}
Entities 2 {Potato}
Entities 0
Entities 1
Entities 0
请注意文档中关于 Finalizers 的问题
The finalizer for x is scheduled to run at some arbitrary time after x becomes unreachable. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program.
关于go - 如何跟踪一个类型的实例数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13308955/