Home > Backend Development > Golang > How Can I Extend Custom Types in Go While Preserving Existing Methods?

How Can I Extend Custom Types in Go While Preserving Existing Methods?

Susan Sarandon
Release: 2024-12-07 09:50:11
Original
1066 people have browsed it

How Can I Extend Custom Types in Go While Preserving Existing Methods?

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

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!

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