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 Structs

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].

Assignment

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.