dqteh7347 2016-04-12 22:23 采纳率: 100%
浏览 7875
已采纳

golang time.Now().Unix()文档与实现之间的差异?

这个链接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

这仅仅是文档中的错误吗?

  • 写回答

1条回答 默认 最新

  • duangua5742 2016-04-12 22:27
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳