

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
click for more info
Not enough gems
Cost: 6 gems
1: Generics in Go
incomplete
2: Why Generics?
incomplete
3: Constraints
incomplete
4: Interface Type Lists
incomplete
5: Parametric Constraints
incomplete
6: Naming Generic Types
incomplete
7: Generic Structs
incomplete
8: Generic Methods
incomplete
9: Generic Methods and Interfaces
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
A generic struct lets us reuse the same fields with different types:
type batch[T any] struct {
items []T
owner string
}
Just like a generic function, the struct declares a type parameter in square brackets. Here, T determines what goes in the items slice.
To use the struct, supply a type argument:
names := batch[string]{
items: []string{"Ada", "Grace"},
owner: "Elrond",
}
counts := batch[int]{
items: []int{100, 250, 500},
owner: "Elros",
}
names.items is a []string, and counts.items is a []int. We wrote one definition, but Go still checks the types of the values we put in each batch. Trying to put an int in names.items won't compile.
Unlike generic function calls, generic struct literals need explicit type arguments: they can't be inferred. That said, the argument can be a type parameter that's already in scope. For example, inside a generic function, we can create a new batch[T].
Textio needs to send the same payload to multiple recipients. The starter code has separate envelope types for email bodies and payment amounts. Let's use one generic type to prepare either kind of delivery.