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
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!