Define a new type of time in golang

huangapple go评论97阅读模式
英文:

Define a new type of time in golang

问题

我想要一个像这样的结构体:

type Person struct {
    Name string
    DateJoined time
}

但是这个结构体无法编译,因为没有time类型,对吗?
我应该使用一个string类型,然后在其中插入时间/日期信息吗?

英文:

I want to have a struct like this:

type Person struct {
    Name string
    DateJoined time
}

But this struct will not compile, because there is no type time, isn't it?
Should I alternatively use a string and insert the time / date information there?

答案1

得分: 95

time不是一个类型,time.Time才是。请参考该包的文档以了解更多类型信息:http://golang.org/pkg/time/

import time

type Person struct {
    Name string
    DateJoined time.Time
}

time不是一个类型,time.Time才是。请参考该包的文档以了解更多类型信息:http://golang.org/pkg/time/

import time

type Person struct {
    Name string
    DateJoined time.Time
}
英文:

time isn't a type. time.Time is. See the package docs for the types: http://golang.org/pkg/time/

import time

type Person struct {
    Name string
    DateJoined time.Time
}

答案2

得分: 5

你需要导入time包,并且使用time.Time。
顺便说一下,当我定义了以下类似于你的自定义类型时,它返回了错误。然后,有人帮助我进行了类型转换(例如,mytime(time.Now()))。

type mytime time.Time

你可以创建自己的包,并且始终导入,以便在你方便的时候使用所有你自己的类型。

英文:

you need to import time package and of course you use time.Time
btw, it returned error when I defined my own type as below with similar reason to you. And, someone helped me to do cast (ex. mytime(time.Now()).

type mytime time.Time

You can make your own package and import always so that all your own type in your convenience

huangapple
  • 本文由 发表于 2014年3月3日 10:54:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/22137885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定