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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图