Preserving Methods while Extending Custom Types
While working with named types for JSON unmarshalling, you may encounter the issue of accessing methods belonging to the underlying type. For instance, defining a named type StartTime, derived from time.Time, and attempting to access its Date() method.
To overcome this limitation and add methods to an existing type while maintaining its original methods, embed the existing type. Embeddings provide a convenient way to promote fields and methods from an embedded anonymous type to the new type.
For example:
type StartTime struct { time.Time }
In this snippet, we embed the time.Time type anonymously within StartTime. According to the Go specification for struct types, all fields and methods within the anonymous field are promoted and can be accessed directly from the enclosing type.
Now, you can seamlessly call Date() and any other methods of time.Time using instances of StartTime. This approach allows you to create named types with extended functionality while preserving the base type's original capabilities.
The above is the detailed content of How Can I Extend Custom Types in Go While Preserving Existing Methods?. For more information, please follow other related articles on the PHP Chinese website!