是否可以编写泛型类型约束,以便该类型包含返回相同类型的函数,还是与普通接口存在相同的问题?示例用例是一个具有可链接方法的生成器.
假设我有一个builder IntFoo
,它有一个SetFoo
方法,负责将foo
字段设置为某个值.Playground link
type IntFoo struct {
foo int
}
func (me *IntFoo) SetFoo(foo int) *IntFoo {
me.foo = foo
return me
}
现在我可能会有几个不同类型的构建器,我想定义一个这样的约束:
type Builder[F any] interface {
SetFoo(F) Builder[F] // this return type is problematic
}
一些函数使用生成器约束类型,如下所示:
// some generic demo function
func demo[E Builder[F], F any](builder E, foo F) {
builder.SetFoo(foo)
return
}
正在try 调用演示函数
e := &IntFoo{}
demo(e, 2)
导致错误:
[compiler InvalidTypeArg] [E] *IntFoo does not implement Builder[int] (wrong type for method SetFoo)
have SetFoo(foo int) *IntFoo
want SetFoo(int) Builder[int]