Home > Net >  Pass type parameter with exact constraint to function with that argument?
Pass type parameter with exact constraint to function with that argument?

Time:11-28

I am starting to use Go generics and have a hard time to understand why this code will not 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 it not be assumed that there is a type constraint on T such that T is the string type?

I understand that I could simply write f(string(p)), but I am still interested in the answer to the question.

CodePudding user response:

This is because of the rules of assignability, in your specific case it's the last rule.

V is a type parameter and T is not a named type, and values of each type in V's type set are assignable to T.

Type string is a named type and because of that, even though each type in T's type set is assignable to string, the type parameter T itself is not assignable to string.

You can compare this with an unnamed type.

func f([]string) {}

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