Home > Article > Backend Development > Do Type Aliases in Go Inherit Methods from Their Underlying Type?
Type Aliases and Method Inheritance
Consider the following code snippet:
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 }
This code demonstrates different ways of creating type aliases and their effects on method inheritance.
Type Alias vs. Type Definition
In Go, there are two types of type declarations: aliases and definitions.
Method Inheritance with Type Aliases
The type alias durWithMethods creates a new type that inherits methods from its underlying type, dur, which in turn embeds time.Duration. Therefore, durWithMethods has access to the String() method from time.Duration.
fmt.Println(d.String()) // works
In contrast, the type alias durWithoutMethods simply renames time.Duration. Since time.Duration is a raw type, it has no methods. Therefore, durWithoutMethods does not have the String() method.
fmt.Println(dWM.String()) // doesn't compile
Type Aliases with Same Underlying Type
A true type alias, which simply renames an existing type, would look like this:
type sameAsDuration = time.Duration
In this case, sameAsDuration has the same methods as time.Duration because it represents the same type.
var sad sameAsDuration fmt.Println(sad.String()) // works
Therefore, the confusion arises due to the subtle difference between type aliases and type definitions, and their impact on method inheritance. Type aliases retain the methods of their underlying type, while type definitions create new types with their own set of methods.
The above is the detailed content of Do Type Aliases in Go Inherit Methods from Their Underlying Type?. For more information, please follow other related articles on the PHP Chinese website!