Home >Backend Development >Golang >Why Can't I Assign `Props[Example]` to `Props[Generic]` in Go Generics?

Why Can't I Assign `Props[Example]` to `Props[Generic]` in Go Generics?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 09:15:11355browse

Why Can't I Assign `Props[Example]` to `Props[Generic]` in Go Generics?

Generic Type Assignment Restrictions

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
}

This code fails to compile with the error:

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

Why is this occurring?

Go generics creates entirely new named types when instantiated with different type arguments. In this case, Props[Example] and Props[Generic] are distinct named types, even though Example implements Generic.

Flexibility through Type Parameterization

To resolve this issue and maintain flexibility, one can instantiate Props with a type parameter:

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

This approach allows for the function to return Props[T] for a specific generic type T that implements Generic.

Summary

In Go generics, instantiating a generic type with different type arguments results in distinct named types. Therefore, attempting to assign one type to another, even if their type arguments satisfy specific conditions, is not permitted. Using type parameterization offers a solution for maintaining flexibility in such scenarios.

The above is the detailed content of Why Can't I Assign `Props[Example]` to `Props[Generic]` in Go Generics?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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