Calling Method of Named Type
You have created a named type, StartTime, which is a wrapper around a time.Time for JSON unmarshalling. However, you are unable to call methods of time.Time, such as Date(), on your StartTime instance.
This is because, by using the type keyword, you have effectively created a new type, rather than extending the existing time.Time type. To preserve the original methods while adding your own, you should use type embedding:
type StartTime struct { time.Time }
With embedding, the fields and methods of the embedded type (time.Time in this case) are "promoted" and can be accessed on the named type (StartTime). Thus, you can now call myStartTime.Date().
Here's an example:
package main import ( "fmt" "time" ) type StartTime struct { time.Time } func main() { s := StartTime{time.Now()} fmt.Println(s.Date()) }
Output:
2009 November 10
The above is the detailed content of How Can I Call time.Time Methods on a Custom Type in Go?. For more information, please follow other related articles on the PHP Chinese website!