

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
Our repeater repeats strings, so you'd expect it to satisfy this interface:
type stringRepeater interface {
Repeat(string) []string
}
Let's try it:
r := repeater{count: 3}
fmt.Println(r.Repeat("Go"))
// [Go Go Go]
var words stringRepeater = r
// doesn't compile
The call works, but the assignment doesn't! Repeat[T any](T) []T doesn't match Repeat(string) []string. Go infers type arguments for calls, not for implementing interfaces.
Move the type parameter to the struct:
type typedRepeater[T any] struct {
count int
}
func (r typedRepeater[T]) Repeat(value T) []T {
result := make([]T, r.count)
for i := range result {
result[i] = value
}
return result
}
The receiver's [T] brings the struct's type parameter into scope. The method declares none of its own, so typedRepeater[string] has the required Repeat(string) []string method:
var words stringRepeater = typedRepeater[string]{count: 3}
fmt.Println(words.Repeat("Go"))
// [Go Go Go]
An interface can have type parameters too, but its methods can't declare their own.