【问题标题】:How to declare a variable of a custom type (like time.Date) in go?如何在go中声明自定义类型的变量(如time.Date)?
【发布时间】:2020-06-09 10:43:05
【问题描述】:

我正在尝试创建这段代码:

var nextWorkday time.Date
// var nextWorkday *time.Date // neither works
yyyy, mm, dd := now.Date()
goalTime, _ := time.ParseDuration(fmt.Sprintf("%fh", *goal))
goalSeconds := int(goalTime.Seconds())
if date.Weekday() != time.Friday { // wait till the next workday (7am + difference)
    nextWorkday = time.Date(yyyy, mm, dd+1, 7, 0, 0+goalSeconds, 0, now.Location())
} else {
    nextWorkday = time.Date(yyyy, mm, dd+3, 7, 0, 0+goalSeconds, 0, now.Location())
}
time.Sleep(nextWorkday)

重要的断点已经是第一行了。我不知道如何声明自定义类型的新变量。现在我得到错误: time.Date is not a type

我做错了什么?任何帮助表示赞赏!

【问题讨论】:

  • 试试time.Time 而不是time.Date
  • 谢谢!这确实已经工作了:) 对我来说似乎有点困惑 time.Date 实际上是一个 time.Time 对象
  • 我应该发布官方答案还是您想要?^^
  • @Tillus 总是查看您正在使用的软件包的文档。这将使您清楚地了解包提供的类型。

标签: object go variables declare


【解决方案1】:

标准time 包中没有time.Date 类型。然而,有一个 time.Time 类型代表一个时间瞬间,“包括”日期。

time.Date() 是一个从提供的日期和时间字段构造time.Time 值的函数。

【讨论】:

    猜你喜欢
    • 2014-09-17
    • 2017-05-17
    • 1970-01-01
    • 2013-02-18
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多