这个链接https://golang.org/pkg/time/#Unix介绍了func Unix(sec int64, nsec int64) Time函数的签名含义, 还会返回一个time对象。
但是下面的程序中止了错误消息:
14: cannot use now.Unix() (type int64) as type time.Time in assignment`
func main() {
var now time.Time
now = time.Now()
fmt.Println(now)
var secs time.Time
secs = now.Unix()
fmt.Println(secs)
}
以下版本的程序生成输出:
func main() {
var now time.Time
now = time.Now()
fmt.Println(now)
// var secs time.Time
secs := now.Unix()
fmt.Println(secs)
}
2016-04-12 18:20:22.566965512 -0400 EDT
1460499622
这仅仅是文档中的错误吗?
The docs are correct, you're looking at the wrong version of Unix
. The method you're using is this; https://golang.org/pkg/time/#Time.Unix it takes no arguments, is called on a time object and returns the unix time as an int64
. The version you're referencing takes two arguments, both int64's, the seconds and nanoseconds? (not positive that's what the nseconds stands for) which represent a time in unix format and it returns a time.Time
So to extend your second example;
func main() {
var now time.Time
now = time.Now()
fmt.Println(now)
// var secs time.Time
secs := now.Unix()
fmt.Println(secs)
t := time.Unix(secs, 0) // get a time from the seconds value which is a unix time
fmt.Println(t)
}
Here's the above in play with one other line added to print the type of secs
. https://play.golang.org/p/KksPPbQ1Jy