将结构字段的初始值设置为 Go 中另一个结构字段的初始值

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

在 Go 中,假设我有这个结构:

type Job struct {
    totalTime int
    timeToCompletion int
}

然后我初始化一个结构对象,如:

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

其中约束是 timeToCompletion 在创建结构时始终等于 totalTime (它们可以稍后更改)。有没有一种方法可以在 Go 中实现这一点,这样我就不必初始化这两个字段?

您不可避免地必须指定该值两次,但惯用的方法是为其创建一个 constructor-like 创建者函数:

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

使用它,您只需在将它传递给我们的 NewJob() 函数时指定一次时间值:

j := NewJob(10)