Model generic receivers and interfaces
Model generic receivers and interfaces
A generic defined type can declare methods whose receiver binds its type parameters. For example, Box[T] in a receiver introduces T using the constraints of the type declaration. An instantiated basic generic interface describes ordinary behavior with type-specific method signatures.
package main
import ( "fmt")
type Box[T any] struct{ v T }
func (b *Box[T]) Set(v T) { b.v = v }func (b Box[T]) Get() T { return b.v }func main() { var b Box[string] b.Set("ready") fmt.Println(b.Get())}Set mutates the original box through a pointer. Get reads the value. The receiver parameter T is not a new independent method type parameter. Its constraint comes from Box.
Expected output:
readyInstantiate an interface
package main
import ( "fmt")
type Source[T any] interface{ Get() T }type Value[T any] struct{ V T }
func (v Value[T]) Get() T { return v.V }func read[T any](s Source[T]) T { return s.Get() }func main() { var s Source[int] = Value[int]{V: 42} fmt.Println(read[int](s))}Source[int] is a basic interface with Get() int. Value[int] satisfies it implicitly. Value[string] does not satisfy Source[int] because the result type differs. Non-basic generic interfaces with type terms remain constraint-only.
Expected output:
42Try it locally
Define Holder[T any] with field V and method Get returning T. Assign Holder[string] containing Go to interface Getter[string] and print Get().
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 06: Model generic receivers and interfaces
Check the lesson objective before moving on.
Where does the receiver T constraint come from in Box[T]?
Which method satisfies Source[int] with Get() T?