Setting the initial value of a structure field to another in Go

In Go, let's say I have this structure:

type Job struct { totalTime int timeToCompletion int } 

and I initialize the struct object as follows:

 j := Job {totalTime : 10, timeToCompletion : 10} 

where the limitation is that timeToCompletion always equal to totalTime when creating the structure (they can change later). Is there a way to achieve this in Go, so that I do not need to initialize both fields?

+5
source share
1 answer

You cannot help but specify the value twice, but in an idiomatic way it would be to create a constructor-creator function for it:

 func NewJob(time int) Job { return Job{totalTime: time, timeToCompletion: time} } 

And using it, you only need to specify the time value once when you pass it to our NewJob() function:

 j := NewJob(10) 
+6
source

Source: https://habr.com/ru/post/1239667/


All Articles