dssqq64884 2018-09-08 06:01
浏览 281
已采纳

为什么在bson.Marshal和bson.Unmarshal之后time.Time不相等?

Why does it output false? I was expecting true...

package main
import (
    "fmt"
    "time"
    "gopkg.in/mgo.v2/bson"
    )

type S struct {
    T time.Time
}
func main() {
    t := S{time.Now()}
    bytes, _ := bson.Marshal(t)
    var dt S
    bson.Unmarshal(bytes, &dt)
    fmt.Println(dt.T.Equal(t.T))
}

go run the above will output false, why Marshal/Unmarshal doesn't preserve the original value?

  • 写回答

1条回答 默认 最新

  • dongxieting9623 2018-09-08 07:11
    关注

    Bson stores time with lower precision than a time.Time, the value returned from Bson may not equal the value you stored. You need to use bson.Now():

    package main
    
    import (
        "fmt"
        "gopkg.in/mgo.v2/bson"
        "time"
    )
    
    type S struct {
        T time.Time
    }
    
    func main() {
        t := S{bson.Now()}
        bytes, _ := bson.Marshal(t)
        var dt S
        bson.Unmarshal(bytes, &dt)
        fmt.Println(dt.T)
        fmt.Println(t.T)
        fmt.Println(dt.T.Equal(t.T))
    }
    

    Output:

    $> go run main.go 
    2018-09-08 10:48:42.45 +0300 MSK
    2018-09-08 10:48:42.45 +0300 MSK
    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?