go - 如何跟踪一个类型的实例数?

标签 go instance destructor

在面向对象的语言中,我使用类变量来跟踪当前生成的实例数量,方法是在构建时递增和在销毁时递减。

我尝试在 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/

相关文章:

c# - 如果结构可以实现 IDisposable,为什么它们不能有析构函数?

c++ - C++中局部变量和返回变量的构造和析构

java - 修复静态方法问题

php - 什么时候使用 getInstance/new class() 比较合理? (PHP)

c - 您如何查询 pthread 以查看它是否仍在运行?

go - 如何在Golang Revel框架下运行角度构建

algorithm - 递归算法中的 Go channel 导致重复值

go - 三个 etcd-go 包有什么区别?

Go Protobuf 精度小数

python - 在python中创建一个匿名类实例