Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the initial value of a struct field to that of another in Go

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?

like image 969
talonx Avatar asked Jan 02 '16 11:01

talonx


Video Answer


1 Answers

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)
like image 193
icza Avatar answered Nov 15 '22 03:11

icza