Home >Backend Development >Golang >Why does a type alias inherit methods from an embedded type but not from a raw type?
Understanding the Impact of Type Aliases on Method Inheritance
Type aliases, a common aspect of programming languages like Go, provide a convenient way to create new identifiers for existing types. However, their behavior in terms of method inheritance can be confusing.
Consider the following Go code:
package main import ( "fmt" "time" ) type dur struct { time.Duration } type durWithMethods dur type durWithoutMethods time.Duration func main() { var d durWithMethods // works ?? fmt.Println(d.String()) var dWM durWithoutMethods fmt.Println(dWM.String()) // doesn't compile }
The code declares three types: dur, durWithMethods, and durWithoutMethods. Type dur is a struct embedding time.Duration. Type durWithMethods is defined as an alias for dur. Type durWithoutMethods, on the other hand, is an alias for time.Duration.
The question arises why durWithMethods inherits the String() method from time.Duration while durWithoutMethods does not.
Type Declarations and Method Inheritance
In Go, type declarations fall into two categories: type definitions and type aliases.
In this case, dur is a type definition while both durWithMethods and durWithoutMethods are type aliases.
Impact on Method Inheritance
When a new type is created using a type definition, like dur, it loses all inherited methods. This means that dur does not inherently possess the String() method of time.Duration. However, when a new type is created using a type alias, like durWithMethods, it inherits all the methods of the underlying type, in this case dur.
Time.Duration and Raw Types
time.Duration is a raw type, meaning it cannot have methods. However, it can be embedded within a struct like dur, which allows the struct to inherit its methods.
Type Alias vs. Direct Alias
durWithoutMethods is a direct alias of time.Duration. This type stripping behavior is unique to direct aliases and does not apply to type aliases like durWithMethods.
In conclusion, while durWithMethods inherits time.Duration's String() method due to it being an alias for a type that embeds time.Duration, durWithoutMethods does not inherit this method because it is a direct alias of a raw type.
The above is the detailed content of Why does a type alias inherit methods from an embedded type but not from a raw type?. For more information, please follow other related articles on the PHP Chinese website!