Home  >  Article  >  Backend Development  >  Passing a type parameter with exact constraints to a function with that parameter?

Passing a type parameter with exact constraints to a function with that parameter?

WBOY
WBOYforward
2024-02-05 23:48:11553browse

Passing a type parameter with exact constraints to a function with that parameter?

Question content

I started using go generics but have a hard time understanding why this code doesn't compile:

func f(string) {}

func xyz[T string](p T) {
    f(p) // Error! Cannot use 'p' (type T) as the type string
}

In function xyz, why can't we assume that t has a type constraint so that t is a string type?

I know I could simply write f(string(p)), but I'm still interested in the answer to the question.


Correct Answer


This is because of the Assignability rule, which in your specific case is the last rule.

v is a type parameter, t is not a named type, and a value of every type in v's type set is assignable to t.

Typestring is a named type, so although every type in the t type set is assignable to string, But the type parameter t itself is not assignable to string.

You can compare it to unnamed types.

func f([]string) {}

func xyz[T []string](p T) {
    f(p) // no issue
}

The above is the detailed content of Passing a type parameter with exact constraints to a function with that parameter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete