I am try to update my Go code from 1.8 to 1.9. but, i got some problem:
package simple_struct
import (
"time"
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"
)
type SimpleStruct struct {
CreateTime time.Time
Other string
}
func NewSimpleStruct() *SimpleStruct {
return &SimpleStruct{
CreateTime: time.Now(),
}
}
func Test(t *testing.T) {
s1 := NewSimpleStruct()
data, err := json.Marshal(s1)
assert.Nil(t, err)
s2 := &SimpleStruct{}
err = json.Unmarshal(data, s2)
assert.Nil(t, err)
assert.Equal(t, s2, s1)
// this is not equal
// output:
/*
Diff:
--- Expected
+++ Actual
@@ -1,3 +1,3 @@
(*simple_struct.SimpleStruct)({
- CreateTime: (time.Time) 2017-12-01 14:54:53.948875421 +0800 CST,
+ CreateTime: (time.Time) 2017-12-01 14:54:53.948875421 +0800 CST m=+0.001827244,
*/
}
It is working in Golang 1.8, but not in Golang 1.9.
I know that Golang 1.9 has update time.Time
, but I do not understand this.
It has long been the case, not just now (go1.9 +), that it is wrong to compare Go
time.Time
s by comparing the implementation (opaquestruct
) with the Go equal operator (==
). For example, as far back as go1.4,go1.9 merely added an additional element, a monotonic value, to the opaque
time.Time
struct
.Always use the
time.Equal
method to asserttime.Time
equality.For example,
Playground: https://play.golang.org/p/VbFV2AcYw-
Output:
Probably to do with monotonic time being wiped by marshalling. See the the package docs