I have a named type, which I needed to make to do some JSON unmarshmaling:
type StartTime time.Time
func (st *StartTime) UnmarshalJSON(b []byte) error {...}
Using the type
keyword you are creating a new type and as such it will not have the methods of the underlying type.
Use embedding:
type StartTime struct {
time.Time
}
Quoting from the Spec: Struct types:
A field or method
f
of an anonymous field in a structx
is called promoted ifx.f
is a legal selector that denotes that field or methodf
.
So all the methods and fields of the embedded (anonymous) fields are promoted and can be referred to.
Example using it:
type StartTime struct {
time.Time
}
func main() {
s := StartTime{time.Now()}
fmt.Println(s.Date())
}
Output (try it on the Go Playground):
2009 November 10