

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
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
You can also make generic methods on non-generic structs in Go 1.27. Say we have this repeater struct:
type repeater struct {
count int
}
It has a Repeat method that creates a new slice with count instances of the given value:
func (r repeater) Repeat[T any](value T) []T {
result := make([]T, r.count)
for i := range result {
result[i] = value
}
return result
}
Now we can reuse it to create slices of different types:
r := repeater{count: 3}
fmt.Println(r.Repeat("Go"))
// [Go Go Go]
fmt.Println(r.Repeat(42))
// [42 42 42]
The struct isn't generic, only the method is!
Textio's inbox mixes event types. Emails and Receipts duplicate the same filtering logic. Replace them with one generic Select method.