Declare generic functions and types
Declare generic functions and types
Generics let one declaration work with several types while preserving static type checking. In Go 1.18+, a type parameter list follows a function or type name. A constraint describes the permitted type arguments. Instantiation substitutes actual types for those parameters.
package main
import ( "fmt")
func identity[T any](v T) T { return v }func main() { fmt.Println(identity[int](7), identity[string]("Go"))}T is a type parameter, any permits all types, and v is an ordinary value parameter. Both calls return their input with its static type preserved; there is no assertion from any to perform.
Expected output:
7 GoInstantiate a generic record
package main
import ( "fmt")
type Pair[T any] struct{ First, Second T }
func main() { p := Pair[string]{First: "tea", Second: "rice"} fmt.Println(p.First, p.Second)}Pair[string] is an instantiated type. Both fields have type string. A generic type generally needs explicit type arguments at its use site; Pair alone is not a usable variable type.
Expected output:
tea riceTry it locally
Define Box[T any] with Value T. Initialize Box[int] with 12 and print Value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 01: Declare generic functions and types
Check the lesson objective before moving on.
What does T represent in func identity[T any](v T) T?
Which is a usable instantiated type?