Assignability of type parameters

June 6, 2023

Let’s finish up our discussion of assignability by looking at how type parameters are special.

Assignability

Additionally, if x’s type V or T are type parameters, x is assignable to a variable of type T if one of the following conditions applies:

  • x is the predeclared identifier nil, T is a type parameter, and x is assignable to each type in T’s type set.
func foo[T *int | *int32](t T) {
	t = nil
}
  • V is not a named type, T is a type parameter, and x is assignable to each type in T’s type set.
func foo[T int | int32](t T) {
	t = 234
}
  • 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.
func foo[V int | int32](x V) {
	var t any = x
}

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Type switches with generics

More live coding today! Join me! And bring your questions. Type switches … A type parameter or a generic type may be used as a type in a case. If upon instantiation that type turns out to duplicate another entry in the switch, the first matching case is chosen. func f[P any](x any) int { switch x.(type) { case P: return 0 case string: return 1 case []P: return 2 case []byte: return 3 default: return 4 } } var v1 = f[string]("foo") // v1 == 0 var v2 = f[byte]([]byte{}) // v2 == 2 The example included is nice, because it shows two examples of the type parameter P being used: Both the first case (case P) and third (case []P) use the type parameter.


Type switching on a non-interface value. Sorta.

Type switches … Cases then match actual types T against the dynamic type of the expression x. As with type assertions, x must be of interface type, but not a type parameter, and each non-interface type T listed in a case must implement the type of x. The types listed in the cases of a type switch must all be different. TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .


Switch expressions

Expression switches … If the switch expression evaluates to an untyped constant, it is first implicitly converted to its default type. The predeclared untyped value nil cannot be used as a switch expression. The switch expression type must be comparable. In this paragraph, “switch expression” refers to the expression that optionally comes after the switch keyword, as in: switch len(x) { So first off, if it’s a untyped constant, it’s first converted to its default type.

Get daily content like this in your inbox!

Subscribe