What's the Difference Between Type Aliasing and Type Definition in Go?

Patricia Arquette
Release: 2024-11-10 22:41:03
Original
389 people have browsed it

What's the Difference Between Type Aliasing and Type Definition in Go?

Type Aliasing vs. Type Definition in Go

In Go, there are two ways to define new types: type aliasing and type definition. While these mechanisms might seem similar at first glance, there are subtle but significant differences between them.

Type Aliasing (type A = string)

Type aliasing creates an alias for an existing type. This means that the new type name (A in this case) becomes a synonym for the original type (string). When using an alias, all the properties and methods of the original type are inherited by the alias. However, it's important to note that you cannot define new methods on a type alias.

Type Definition (type A string)

Type definition, on the other hand, creates a new type altogether. While it may share the same underlying representation as another type (such as string in this case), it is a distinct type with its own set of properties and methods. Type definitions allow you to define custom methods on the new type, and reflection will recognize the new type separately from the underlying type.

Example

To illustrate the difference, consider the following code:

package main

import (
    "fmt"
)

type A = string
type B string

func (b B) CustomMethod() {
    fmt.Println("Custom method called on B")
}

func main() {
    var a A = "hello"
    var b B = "hello"
    fmt.Printf("a is %T\nb is %T\n", a, b)
    b.CustomMethod() // Legal
    // a.CustomMethod() // Compile-time error
}
Copy after login

In this example, type A is an alias for string, so a is of type string. Type B is a new type defined from string, which allows us to define a custom method on it (CustomMethod). The type checker will correctly identify b as a B type, and the CustomMethod method can be invoked on it. However, trying to invoke CustomMethod on a would result in a compile-time error because type aliases do not inherit methods.

The above is the detailed content of What's the Difference Between Type Aliasing and Type Definition 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