In Go, let's say I have this struct:
type Job struct {
totalTime int
timeToCompletion int
}
and I initialize a struct object like:
j := Job {totalTime : 10, timeToCompletion : 10}
where the constraint is that timeToCompletion
is always equal to totalTime
when the struct is created (they can change later). Is there a way to achieve this in Go so that I don't have to initialize both fields?
You can't avoid having to specify the value twice, but an idiomatic way would be to create a constructor-like creator function for it:
func NewJob(time int) Job {
return Job{totalTime: time, timeToCompletion: time}
}
And using it you only have to specify the time value once when passing it to our NewJob()
function:
j := NewJob(10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With