为了账号安全,请及时绑定邮箱和手机立即绑定

泛型:约束具有返回自身的函数的类型

泛型:约束具有返回自身的函数的类型

Go
扬帆大鱼 2022-11-28 14:48:37
是否可以编写一个泛型类型约束,以便该类型包含一个返回相同类型的函数,或者它是否与普通接口存在相同的问题?示例用例是具有可链接方法的构建器。假设我有一个构建器IntFoo,它有一个SetFoo方法负责将foo字段设置为某个值。游乐场链接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}和一些使用 Builder 约束类型的函数,如下所示:// some generic demo functionfunc demo[E Builder[F], F any](builder E, foo F) {    builder.SetFoo(foo)    return}尝试调用演示函数    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]
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

你想从你的方法返回原始类型E- 而不是Builder接口:


type Builder[F, E any] interface {

    SetFoo(F) E

}

然后返工demo,因此将所需的类型E传递给Builder类型约束:


func demo[E Builder[F, E], F any](bldr E, foo F) E {

    return bldr.SetFoo(foo)

}

https://go.dev/play/p/2K4D_nzMwU2


v := demo(e, 2)

fmt.Printf("%[1]T : %+[1]v\n", v) // *main.IntFoo : &{foo:2}


查看完整回答
反对 回复 2022-11-28
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信