Home >Backend Development >Golang >Why Can't I Assign Go Generic Types with Different Arguments?
In Go, generic interfaces and implementations don't allow direct assignment across different type arguments.
Let's consider a simplified example:
// Abstract type Generic interface { ID() string } type Props[G Generic] struct{} // Example type Example struct { id string } func (example Example) ID() string { return example.id } var ExampleProps = Props[Example]{} // Problem func Problem() Props[Generic] { return ExampleProps }
This code throws a compilation error stating that Props[Example] cannot be assigned to Props[Generic] in the return statement. This is because when instantiating generic types with different type arguments, Go creates distinct named types.
Consider the following function:
func Problem() Props[Generic] { return ExampleProps }
It instantiates Props with Generic as the type argument. Consequently, Props[Example] and Props[Generic] become two different types, even though Example implements Generic. Therefore, assigning Props[Example] to Props[Generic] is invalid, regardless of their type parameters.
To fix this issue, one option is to instantiate Props with a type parameter that satisfies the Generic constraint:
// adding a field to make this a bit less contrived type Props[G Generic] struct{ Value G } // Props instantiated with T, adequately constrained func Problem[T Generic](v T) Props[T] { return Props[T]{ Value: v } } func main() { a := Problem(Example{}) fmt.Println(a) }
In this example, Props is instantiated with a type parameter T that conforms to the Generic interface. This allows for values of type Props[Example] to be assigned to Props[Generic] and ensures type safety.
The above is the detailed content of Why Can't I Assign Go Generic Types with Different Arguments?. For more information, please follow other related articles on the PHP Chinese website!