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

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!

Assignment

Textio's inbox mixes event types. Emails and Receipts duplicate the same filtering logic. Replace them with one generic Select method.