英文:
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中实现这一点,以便我不必初始化两个字段?
英文:
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?
答案1
得分: 6
你可以避免重复指定值,但一种惯用的方法是为其创建一个类似构造函数的创建函数:
func NewJob(time int) Job {
return Job{totalTime: time, timeToCompletion: time}
}
使用这个函数时,只需在传递给NewJob()
函数时指定一次时间值:
j := NewJob(10)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论