是否可以编写泛型类型约束,以便该类型包含返回相同类型的函数,还是与普通接口存在相同的问题?示例用例是一个具有可链接方法的生成器.

假设我有一个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]

推荐答案

您希望返回原始类型,而不是为方法定义的interface.所以这会起作用:

type Builder[F any, E any] interface {
    SetFoo(F) E
}

再稍微修改一下:

func demo[F any, E Builder[F, E]](builder E, foo F) E {
    return builder.SetFoo(foo)
}

https://go.dev/play/p/jkD9xTUDbjV

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

Go相关问答推荐

有没有更简单的方法在Go中编写这个逻辑?

如何在定制普罗米修斯出口商中测试动态计量注册?

如何模拟嵌入. FS?

你能帮我优化一个golang代码关于函数CrossPointTwoRect

GetSecretValue,get identity:get credentials:无法刷新缓存的凭据

Golang html/模板&需要错误数量的参数1在模板中使用';调用';获得0&q;

map 中的多个函数类型,Golang

在 Go 中使用 Apache Arrow 按时间间隔对事件进行分区

Go test "-run -" 标志执行测试更快

如何解决我的 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?

替换字符串中的最后一个字符

golang:解组动态 YAML 注释

Wire google Inject with multi return from provider 函数

获取切片元素的地址是否意味着 Go 中元素的副本?

从 Makefile 运行时权限被拒绝

try 与 golang testify/suite 并行运行测试失败

Golang prometheus 显示自定义指标

Golang Echo Labstack 如何在模板视图中调用函数/方法

如何从 Go 1.18 中的单个方法返回两种不同的具体类型?

golang jwt.MapClaims 获取用户ID