In golang, say I have a type that needs some setup done on it before use beyond just setting default values. ex:
type dice struct {
input string
count int
sides int
result int
}
func (d *dice) Roll() {
//initialize random seed
rand.Seed(time.Now().UnixNano())
for i := 0; i < d.count; i++ {
d.result = d.result + rand.Intn(d.sides)+1)
}
}
Simple example but say if I wanted to have d.Roll() called automatically when creating an instance of the 'dice' type is there a way to do that? More in line with the issue I'm trying to solve, say I wanted the rand.Seed(time.Now().UnixNano()) bits to be called automatically before I call Roll() is there an idiomatic golang way to do this?
Basically "How do you handle constructor functionality in golang?" is my question. Is there an interface for this I can add?
There is not. But the common, and I would say idiomatic, thing to do is to put a func NewDice() dice
in your package and then you can just call it to get an instance. Do your set up there. It serves the same purpose as a constructor. It's pretty common to have package level methods like NewMyType
that do initilization and return and instance.
No, Go doesn't provide this kind of interface. You just can't use a constructor like you would do in C++ by example.
The current idiom is to create a function
NewX(args...) X // or *X
in which you can setup your struct as you want. In your case, it could look like this:
func NewDice() dice {
var d dice
d.Roll()
return d
}