Home >Backend Development >Golang >Why Can't I Call Methods on a Named Type in Go, and How Can Embedding Solve This?

Why Can't I Call Methods on a Named Type in Go, and How Can Embedding Solve This?

DDD
DDDOriginal
2024-12-14 16:00:19386browse

Why Can't I Call Methods on a Named Type in Go, and How Can Embedding Solve This?

Calling Methods on Named Types

In Go, named types are new data types created from existing ones. This can be useful for adding custom methods to the underlying type, such as in the case of unmarshalling JSON data. However, when the named type is created in the manner shown below, it loses the ability to call methods of the underlying type:

type StartTime time.Time

For instance, attempting to call the Date() method on myStartTime results in an error: myStartTime.Date undefined (type my_package.StartTime has no field or method Date).

Solution: Embracing Embeddings

To resolve this issue and preserve the original methods of the underlying type, one can utilize embedding. By embedding the underlying type, the named type inherits all its methods and fields. This process is demonstrated below:

type StartTime struct {
    time.Time
}

In this scenario, all methods and fields of time.Time are "promoted" and become accessible through the named type. Consequently, calling Date() on s, a variable of type StartTime, no longer elicits an error.

Example Showcase:

type StartTime struct {
    time.Time
}

func main() {
    s := StartTime{time.Now()}
    fmt.Println(s.Date())
}

This code yields the following output:

2009 November 10

By employing embedding, you can effortlessly extend the capabilities of existing types while retaining their original functionality.

The above is the detailed content of Why Can't I Call Methods on a Named Type in Go, and How Can Embedding Solve This?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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