kra*_*r65 2 datetime struct go
我刚开始使用Go,在我编写的第一个程序中,我打印了一个结构,该结构还显示了
{wall:0 ext:63533980800 loc:<nil>}
Run Code Online (Sandbox Code Playgroud)
对似乎是类型的东西感到困惑time.Time(),谷歌搜索将我带到了Go源代码的这一部分,其中在注释中解释了“挂钟”和“单调时钟”之间的区别。
因此,为了进行隔离测试,我创建了一个新的简约程序:
package main
import (
"fmt"
"time"
)
type TheStruct struct {
the_time time.Time
}
func main() {
the_struct := TheStruct{time.Now()}
fmt.Println(the_struct)
fmt.Printf("%+v\n", the_struct)
fmt.Println(the_struct.the_time)
fmt.Println()
the_struct_2 := TheStruct{time.Unix(1505099248, 200)}
fmt.Println(the_struct_2)
fmt.Printf("%+v\n", the_struct_2)
fmt.Println(the_struct_2.the_time)
}
Run Code Online (Sandbox Code Playgroud)
打印出以下内容:
{{13719544904843884912 534246 0x1140680}}
{the_time:{wall:13719544904843884912 ext:534246 loc:0x1140680}}
2017-09-11 05:08:11.35635032 +0200 CEST m=+0.000534246
{{200 63640696048 0x1140680}}
{the_time:{wall:200 ext:63640696048 loc:0x1140680}}
2017-09-11 05:07:28 +0200 CEST
Run Code Online (Sandbox Code Playgroud)
所以我想知道这里的两件事:
the_struct.the_time)时更常用的日期时间表示法相比,为什么将结构的一部分打印为墙上时钟的时间呢?<nil>为该位置打印出来是一个问题吗?我将如何解决呢?在您的结构中不打印格式化时间的原因是未在未导出的字段上调用String方法(请参阅https://golang.org/pkg/fmt/):
打印结构时,fmt无法并且因此不会在未导出的字段上调用诸如Error或String之类的格式化方法。
更改结构以导出字段(首字母大写)使它调用String方法:
package main
import (
"fmt"
"time"
)
type TheStruct struct {
The_time time.Time
}
func main() {
the_struct := TheStruct{time.Now()}
fmt.Println(the_struct)
fmt.Printf("%+v\n", the_struct)
fmt.Println(the_struct.The_time)
fmt.Println()
the_struct_2 := TheStruct{time.Unix(1505099248, 200)}
fmt.Println(the_struct_2)
fmt.Printf("%+v\n", the_struct_2)
fmt.Println(the_struct_2.The_time)
}
Run Code Online (Sandbox Code Playgroud)
输出:
{2009-11-10 23:00:00 +0000 UTC m=+0.000000000}
{The_time:2009-11-10 23:00:00 +0000 UTC m=+0.000000000}
2009-11-10 23:00:00 +0000 UTC m=+0.000000000
{2017-09-11 03:07:28.0000002 +0000 UTC}
{The_time:2017-09-11 03:07:28.0000002 +0000 UTC}
2017-09-11 03:07:28.0000002 +0000 UTC
Run Code Online (Sandbox Code Playgroud)
在操场上:https : //play.golang.org/p/r0rQKBlpWc
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |