Calling Methods of Named Types
In Go, named types created using the type keyword are distinct types from their underlying types. As a result, methods belonging to the underlying type cannot be invoked directly on the named type.
To resolve this issue and extend a named type with additional methods while preserving its original functionality, the technique of embedding can be employed. By embedding the underlying type anonymously within the named type, the methods and fields of the embedded type become promoted and accessible within the named type.
For instance, if you have a named type StartTime that wraps a time.Time value:
type StartTime time.Time func (st *StartTime) UnmarshalJSON(b []byte) error {...}
To access the methods of time.Time on the StartTime type, embed time.Time anonymously within StartTime:
type StartTime struct { time.Time }
Now, you can call methods such as Date() on StartTime as if they were directly defined on the type:
myStartTime.Date()
This approach allows for seamless extension of named types with additional methods while retaining the original functionality of the underlying type.
The above is the detailed content of How Can I Call Underlying Type Methods on a Named Type in Go?. For more information, please follow other related articles on the PHP Chinese website!