duanpo7796 2018-09-07 06:55
浏览 69
已采纳

表示可选时间的惯用方式。结构中的时间

I've read both Optional Parameters? and Golang pass nil as optional argument to a function?

And still wonder if my case is more specific.

What I've got is:

type Periodical struct {
    Interval *interval.Interval
    StartsAt time.Time
    EndsAt   time.Time
}

to represent periodical event which has a start date and may or may not have an end date (periodical event runs for indefinite amount of time).

eachYear := Periodical{
    interval.Years(1),
    StartsAt: time.Parse("2 Jan 2006", "1 Jan 1970")}

Will throw

periodical/periodical.go:31:39: cannot use nil as type time.Time in field value

Which is understood, - I didn't specify EndsAt time.Time.

But what do I really do there then?

Am I forced to have a special flag to neglect EndsAt like so?

type Periodical struct {
    Interval     *interval.Interval
    StartsAt     time.Time
    EndsAt       time.Time
    isIndefinite bool       // This looks ugly already
}

and then if I want Yearly / Anually I do something like

eachYear := Periodical{
    interval.Years(1),
    time.Parse("2 Jan 2006", "1 Jan 1970"),
    time.Parse("2 Jan 2006", "1 Jan 1970"),
    isIndefinite: true}

Although, I can then account for this flag in business logic, but this EndsAt set to the same (or any other) date looks kind of dull.

I also define a method on periodical package which allows to have a shorthand periodical event like so:

func Monthly(s, e time.Time) Periodical {
    return Periodical{StartsAt: s, EndsAt: e, Interval: interval.Months(1)}
}

What do I do to omit end (the second param)? Am I forced to either have separate method for that or do something that looks a bit funky and lacks readability:

func Monthly(s time.Time, end ...time.Time) Periodical {
    if len(end) == 1  {
        return Periodical{
            StartsAt: s,
            EndsAt: end[0],
            Interval: interval.Months(1),
            isIndefinite: false}
    } else if len(end) > 1 {
        panic("Multiple end dates are not allowed, don't know what to do with those")
    } else {
        return Periodical{
            StartsAt: s,
            EndsAt: time.Now(),
            Interval: interval.Months(1),
            isIndefinite: true}
    }
}

Although it does the trick, it looks ugly, isn't it? My concise one-liner is now scattered along several lines of code.

So, that's why I wonder, what's the go's idiomatic way of achieving what I'm trying to do?

  • 写回答

1条回答 默认 最新

  • duansai1314 2018-09-07 07:05
    关注

    time.Time is a struct. Its zero value–although being a valid time value–is like never used. You can utilize the zero value time to signal the missing or undefined time value. There is even a Time.IsZero() method which tells you if a time.Time value is the zero value.

    Note that the zero value time is not Jan 1, 1970 like in some other languages, but Jan 1, year 1, as you can see on the Go Playground. This is also documented at time.Time:

    The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.

    Also, when creating a Periodical value, use keyed composite literal, and you can omit fields which you don't want to set, thus leaving them at their zero value:

    eachYear := Periodical{
        Interval: interval.Years(1),
        StartsAt: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
    }
    

    Note that you can't use time.Parse() in this composite literal as that returns 2 values (a time.Time and an error). Either use time.Date() as in the above example, or create the time value prior (handle error), and just use the time value.

    To tell if EndsAt is specified:

    if eachYear.EndsAt.IsZero() {
        fmt.Println("EndsAt is missing")
    }
    

    Should you need to zero an already set (non-zero) time value, you may use the time.Time{} composite literal:

    eachYear.StartsAt = time.Time{}
    

    Also note though that when marshaling a time.Time value, even if it's the zero value (since it is a valid time value), it will be sent even if you use the omitempty option. In those cases you must use a *time.Time pointer or write custom marshalers. For details, see Golang JSON omitempty With time.Time Field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图