Home > Backend Development > Golang > 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
Release: 2024-02-05 23:48:11
forward
623 people have browsed it

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

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

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!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template