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

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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器