Home > Backend Development > Golang > Why Can't Go's Generic Types with Different Type Arguments Be Assigned to Each Other?

Why Can't Go's Generic Types with Different Type Arguments Be Assigned to Each Other?

Linda Hamilton
Release: 2024-12-19 11:22:09
Original
587 people have browsed it

Why Can't Go's Generic Types with Different Type Arguments Be Assigned to Each Other?

Why Can't Generic Instances of the Same Type Be Assigned to Each Other?

Go prohibits assigning instances of generic types with different type arguments to each other, even if the type arguments fulfill interface relationships. To illustrate this, consider the following code:

type Generic interface {
    ID() string
}

type Props[G Generic] struct{}

type Example struct {
    id string
}

func (example Example) ID() string {
    return example.id
}

var ExampleProps = Props[Example]{}

func Problem() Props[Generic] {
    return ExampleProps
}
Copy after login

Executing this code results in a compilation error:

cannot use ExampleProps (variable of type Props[Example]) as Props[Generic] value in return statement
Copy after login

This error arises because instantiating a generic type with a new type argument creates a distinct type. Specifically:

  • Props[Example] is one named type, and
  • Props[Generic] is another named type.

These two types are not interchangeable, despite the fact that Example implements Generic. Therefore, assigning ExampleProps (an instance of Props[Example]) to Props[Generic] is invalid.

This behavior extends to generics instantiated with any. any is merely a static type aliasing an empty interface: interface{}. It is not equivalent to "any type" or T. Thus, a type instantiated with any is not assignable to a type instantiated with another specific type.

To resolve this issue, you can instantiate Props with a type parameter, ensuring that both the input and output types of the function are consistent. For example:

type Props[G Generic] struct{ Value G }

func Problem[T Generic](v T) Props[T] {
    return Props[T]{ Value: v }
}

func main() {
    a := Problem(Example{})
    fmt.Println(a)
}
Copy after login

The above is the detailed content of Why Can't Go's Generic Types with Different Type Arguments Be Assigned to Each Other?. 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