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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号