Home >Backend Development >Golang >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 }
Executing this code results in a compilation error:
cannot use ExampleProps (variable of type Props[Example]) as Props[Generic] value in return statement
This error arises because instantiating a generic type with a new type argument creates a distinct type. Specifically:
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) }
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!