【问题标题】:Time type in Golang not recognized by compiler [closed]编译器无法识别Golang中的时间类型[关闭]
【发布时间】:2021-05-07 08:09:02
【问题描述】:

我正在尝试在 Go 中处理一个结构,它有两个属性需要我作为时间戳:

type Asset struct {
    Owner     string `json:"owner"`
    Key       string `json:"key"`
    StartDate Time   `json:"startDate"`
    EndDate   Time   `json:"endDate"`
    Type      string `json:"type"`
    Amount    int    `json:"amount"`
    Facility  string `json:"facility"`
    State     string `json:"state"`
}

我导入了“time”包,但是编译器给了我一个 Time 类型的错误:

“未声明名称:时间编译器未声明名称”

关于为什么会发生这种情况的任何提示?

【问题讨论】:

标签: go struct time


【解决方案1】:

Time 类型在 time 包中定义。你必须import那个包:

import "time"

并使用qualified identifier 来引用导出的Time 类型,即packagename.Identifier,在本例中为time.Time

type Asset struct {
    Owner     string    `json:"owner"`
    Key       string    `json:"key"`
    StartDate time.Time `json:"startDate"`
    EndDate   time.Time `json:"endDate"`
    Type      string    `json:"type"`
    Amount    int       `json:"amount"`
    Facility  string    `json:"facility"`
    State     string    `json:"state"`
}

Go Playground 上尝试工作代码。

查看相关:Getting a use of package without selector error

【讨论】:

    【解决方案2】:

    当你定义带有时间戳的结构时,它应该是time.Time

    参考https://golang.org/pkg/time/和时间结构https://golang.org/src/time/time.go?s=6278:7279#L117

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2023-03-11
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多