Why Doesn\'t a Direct Type Alias Inherit Methods in Go?

Linda Hamilton
Release: 2024-11-19 09:54:03
Original
132 people have browsed it

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
}
Copy after login

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
Copy after login

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!

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