When Do Type Aliases and Type Definitions in Go Differ in Method Inheritance?

Linda Hamilton
Release: 2024-11-19 18:51:03
Original
451 people have browsed it

When Do Type Aliases and Type Definitions in Go Differ in Method Inheritance?

Type Aliases vs. Type Definitions

In Go, type declarations can be classified into two categories: alias declarations and type definitions. Understanding this distinction is crucial to comprehending the curious behavior of type aliases like durWithoutMethods and sameAsDuration.

Alias Declarations

Alias declarations merely create a new identifier for an existing type. This new identifier is interchangeable with the original name. For instance, type dur = time.Duration creates an alias for time.Duration. Using dur and time.Duration to declare variables results in identical behavior.

Type Definitions

In contrast, type definitions create new types. They strip away all methods from the underlying type. This means that if you define a type type x struct { y time.Duration }, x will not inherit any methods of time.Duration. This is because time.Duration is a raw type, a type with no methods attached.

Applying this to the Examples

  • durWithMethods dur: This alias declaration creates a new type durWithMethods that has dur as its underlying type. Since dur embeds time.Duration, dur and durWithMethods inherit Duration.String().
  • durWithoutMethods time.Duration: This type definition creates a new type durWithoutMethods that is separate from time.Duration. As a result, durWithoutMethods does not inherit Duration.String().
  • type sameAsDuration = time.Duration: This type alias declaration denotes that sameAsDuration and time.Duration are the same type. Therefore, sameAsDuration also has the String() method.

The above is the detailed content of When Do Type Aliases and Type Definitions in Go Differ in Method Inheritance?. 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