I have a custom time format which I use to properly encode/decode json. However whenever I need to do a time computation I need to do a cast. Is this the right way? It feels a b
Presumably you have type Mytime time.Time
. If instead you embedded it:
type MyTime struct {
time.Time
}
Then you could have:
func (t MyTime) MarshalJSON() ([]byte, error) {
… whatever …
}
and still access all of time.Time
's methods.
E.g. something like:
t := MyType{time.Now()}
t.Time = t.Add(time.Hour)
Fuller example showing differences between embedded and non-embedded custom time types. Note that embedding still doesn't allow for transparent inter-use with things that expect a time.Time
value. (The reason for making these types, e.g. to add a MarshalJSON
method has been omitted here).
package main
import (
"fmt"
"time"
)
type YourTime time.Time
type MyTime struct{ time.Time }
// Some random functions, perhaps in a third party package,
// that deals with time.Time values.
func fn(t time.Time) {
fmt.Println("fn got:", t)
}
func fn2() time.Time {
return time.Unix(14e8, 0)
}
func main() {
var t1 = YourTime(time.Now())
//t1 = t1.Add(time.Hour) // compiler error
t1 = YourTime(time.Time(t1).Add(time.Hour))
fmt.Println("ugly t1:", t1)
fmt.Println("nice t1:", time.Time(t1))
//fn(t1) // compiler error
fn(time.Time(t1))
//t1 = fn2() // compiler error
t1 = YourTime(fn2())
var t2 = MyTime{time.Now()}
// t2 = t2.Add(time.Hour) // compiler error
t2.Time = t2.Add(time.Hour)
fmt.Println("t2:", t2)
//fn(t2) // compiler error
fn(t2.Time)
//t2 = fn2() // compiler error
t2.Time = fn2()
}
Playground
Output:
ugly t1: {63393494400 0 0x1c9340}
nice t1: 2009-11-11 00:00:00 +0000 UTC
fn got: 2009-11-11 00:00:00 +0000 UTC
t2: 2009-11-10 23:00:00 +0000 UTC
fn got: 2009-11-10 23:00:00 +0000 UTC