Home > Backend Development > Golang > Why Can't I Assign Go Generic Types with Different Arguments?

Why Can't I Assign Go Generic Types with Different Arguments?

Susan Sarandon
Release: 2024-12-20 05:56:10
Original
150 people have browsed it

Why Can't I Assign Go Generic Types with Different Arguments?

Assigning 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
}
Copy after login

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
}
Copy after login

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)
}
Copy after login

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!

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