In object oriented languages I use class variables to track how many instances are currently spawned by incrementing on construction and decrementing on destruction.
I try to implement similar behaviour in 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
}
and that works half way as I can not decrement the counter via a destructor.
Can I somehow mimic object destruction?
How would I keep track of instance count correctly?
You can use runtime.SetFinalizer like this. See here for playground version.
This prints
Note this from the docs for gotchas with Finalizers