Today I’ll be live-streaming again, doing TDD on an open-source project. I hope you can join!
Conversions
…
Additionally, if
T
orx
’s typeV
are type parameters,x
can also be converted to typeT
if one of the following conditions applies:
- Both
V
andT
are type parameters and a value of each type inV
’s type set can be converted to each type inT
’s type set.- Only
V
is a type parameter and a value of each type inV
’s type set can be converted toT
.- Only
T
is a type parameter andx
can be converted to each type inT
’s type set.
So in other words, conversion to/from a type parameter is not possible if there’s a possibility that the conversion would be impossible.
Let’s illustrate with examples.
func foo[T int | int8, V int | int16](x V) T {
return T(x) // Allowed, All types of V can be converted to all types of T
}
func foo2[T int | int8, V int | int16 | string](x V) T {
return T(x) // Not allowed: cannot convert x (variable of type V constrained by int | int16 | string) to type T: cannot convert string (in V) to type int (in T)
}
func bar[V int | int16] (x V) int {
return int(x) // Allowed: Each type of V can be converted to int
}
func bar2[V int | int16] (x V) bool {
return bool(x) // Not allowed: cannot convert x (variable of type V constrained by int | int16) to type bool: cannot convert int (in V) to type bool
}
func baz[T int | int8] (x int) T {
return T(x) // Allowed: x can be converted to each of T's types
}
func baz2[T int | int8 | bool] (x int) T {
return T(x) // Not allowed: cannot convert x (variable of type int) to type T: cannot convert int to type bool (in T)
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)