skip to content
Alvin Lucillo

Method-based generic constraint

/ 1 min read

Unlike earlier constraints where we require comparability or underlying type, method-based constraint uses an interface as the constraint, which checks if the type satisfies a behavior.

In the example below, the generic function requires that the type has a receiver method with signature ID() string. If a type does not implement the method, you will see a compile-time error shown also below.

type ModelIdentifier interface {
	ID() string
}

type Model1 struct{}

func (Model1) ID() string {
	return "1"
}

type Model2 struct{}

func main() {
	fmt.Println(ProcessModel(Model1{}))
	fmt.Println(ProcessModel(Model2{})) // compile-time error: in call to ProcessModel, T (type Model2) does not satisfy ModelIdentifier (missing method ID)
}

func ProcessModel[T ModelIdentifier](v T) string {
	return v.ID()
}