dongshuo2752 2016-01-02 11:11
浏览 139
已采纳

在Go中将struct字段的初始值设置为另一个

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条回答 默认 最新

  • 普通网友 2016-01-02 11:25
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料