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

huangapple go评论81阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2016年1月2日 19:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/34565202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定