Home > Backend Development > Golang > How Can I Call Underlying Type Methods on a Named Type in Go?

How Can I Call Underlying Type Methods on a Named Type in Go?

Susan Sarandon
Release: 2024-12-06 04:43:09
Original
608 people have browsed it

How Can I Call Underlying Type Methods on a Named Type in Go?

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 {...}
Copy after login

To access the methods of time.Time on the StartTime type, embed time.Time anonymously within StartTime:

type StartTime struct {
    time.Time
}
Copy after login

Now, you can call methods such as Date() on StartTime as if they were directly defined on the type:

myStartTime.Date()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template