Home > Article > Backend Development > Why Doesn\'t a Direct Type Alias Inherit Methods in Go?
Understanding Type Aliases in Go
In Go, type aliases can be confusing. The following code exemplifies this:
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 }
Why does the direct alias durWithoutMethods not inherit any methods, unlike durWithMethods?
Type Declarations and Aliases
To understand this, we need to differentiate between type declarations and type aliases. A type declaration creates a new type, stripping all methods from its underlying type. A type alias, on the other hand, simply binds a new identifier to an existing type.
Method Resolution
In the case of durWithMethods, a new type durWithMethods is created with dur as its underlying type. As dur embeds time.Duration, methods of time.Duration are promoted to dur. Therefore, d.String() can be called using the shorthand d.Duration.String().
Stripping of Methods
However, in durWithoutMethods, the direct alias of time.Duration, all methods are stripped. Since Duration.String() is a method of time.Duration, it is not inherited by durWithoutMethods.
True Type Aliases
A true type alias, on the other hand, is denoted using the = sign:
type sameAsDuration = time.Duration
This creates an alias for time.Duration without stripping methods. Hence, sad.String() can be called similarly to d.String().
The above is the detailed content of Why Doesn\'t a Direct Type Alias Inherit Methods in Go?. For more information, please follow other related articles on the PHP Chinese website!