We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Generic Methods and Interfaces

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.

Fix the Type on the Struct

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.