Puzzle 9 Explanation: Go Time API
Understand how time.Time works.
We'll cover the following...
We'll cover the following...
Try it yourself
Try executing the code below to see the result for yourself.
Go (1.16.5)
package mainimport ("encoding/json""fmt""log""time")func main() {t1 := time.Now()data, err := json.Marshal(t1)if err != nil {log.Fatal(err)}var t2 time.Timeif err := json.Unmarshal(data, &t2); err != nil {log.Fatal(err)}fmt.Println(t1 == t2)}
Explanation
You might expect this code to fail since there’s no time type in the JSON format, or you might expect the comparison to succeed.
Go’s encoding/json package lets us define custom JSON serialization for types that JSON does not support. We do that by implementing json.Marshaler
and json.Unmarshaler
interfaces. Go’s ...