登录
首页 >  Golang >  Go问答

在 go (1.18) 中对泛型进行多态实现的最佳方法是什么?

来源:stackoverflow

时间:2024-02-12 14:45:23 220浏览 收藏

大家好,今天本人给大家带来文章《在 go (1.18) 中对泛型进行多态实现的最佳方法是什么?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我想创建一个对其内部数据通用的向量类型,但在给定输入类型的情况下,方法的实现方式可能有所不同。

type supportedtype interface {
         ~int64 | ~uint64 |  ~float64 | string | bool | time.time
}

type vec[t supportedtype] struct {
    data []t
}

我想根据类型在函数上添加不同的实现。例如:

func (vec Vec[T]) Sort() {
    ...
}

在大多数泛型类型中,< 都可以正常工作。但是,如果 t -> time.time 我想使用 before 方法,如果 t --> bool 那么我希望所有假值都在 true 之前。

我对如何实现这一点有一些想法,但是在新的仿制药世界中什么会被认为是“惯用的”?我的应用程序对性能敏感。

对所有具有相同功能的类型使用类型联合是行不通的(https://play.golang.com/p/qwe-xtewpjl)。

在特定类型的结构中嵌入容器确实有效(https://play.golang.com/p/j0ar48mto-a),但需要使用接口,这意味着示例函数中的 lessval 不能被内联。如果类型联合中的子集之间没有清晰的划分,它也可能无法很好地工作。


正确答案


顺便说一句,已经有一个用于排序的库

https://pkg.go.dev/golang.org/x/exp/slices#Sort

1。您可以使用泛型创建接口,然后对其键入断言。

示例:

type lesser[t supportedtype] interface {
    less(t) bool
}

type vec[t supportedtype] []t

func (vec vec[t]) less(a, b int) bool {
    return any(vec[a]).(lesser[t]).less(vec[b])
}

func main() {
    vs := vec[string]([]string{"a", "b", "c", "d", "e"})
    vb := vec[bool]([]bool{false, true})
    fmt.println(vs.less(3, 1))
    fmt.println(vb.less(0, 1))
}

playground 1

2。您可以将类型保存在 vec 上。

示例:

type lesser[t supportedtype] interface {
    less(t) bool
}

type vec[t supportedtype, l lesser[t]] []t

func (vec vec[t, l]) less(a, b int) bool {
    return any(vec[a]).(l).less(vec[b])
}

func main() {
    vs := vec[string, string]([]string{"a", "b", "c", "d", "e"})
    fmt.println(vs.less(3, 1))
}

playground 2

3。嵌套类型约束

谢谢@blackgreen

示例:

type supportedtype interface {
    int8 | time | bool | string
}

type lesser[t supportedtype] interface {
    less(t) bool
}

type vec[t interface {
    supportedtype
    lesser[t]
}] []t

func (vec vec[t]) less(a, b int) bool {
    return vec[a].less(vec[b])
}

func main() {
    vs := vec[string]([]string{"a", "b", "c", "d", "e"})
    fmt.println(vs.less(3, 1))
}

playgrond 3

基准:

benchmark 1 : 28093368          36.52 ns/op       16 b/op          1 allocs/op

benchmark 2 : 164784321          7.231 ns/op           0 b/op          0 allocs/op

benchmark 3 : 212480662          5.733 ns/op           0 b/op          0 allocs/op

embedding a container inside type specific structs:
benchmark 4 : 211429621          5.720 ns/op           0 b/op          0 allocs/op

哪一个最适合您取决于您​​。但 imo 数字 3 是最好的。

就个人而言,我认为最好不要在联合中包含许多彼此不相关的类型,因为它们不会共享许多常见操作,并且您结束编写特定于类型的代码。那么使用泛型有什么意义......?

无论如何,可能的策略取决于 supportedtype 约束的类型集中包含的内容,以及您想要对这些内容执行的操作:

只有精确类型,没有方法

t 上使用类型开关并运行对具体类型有意义的任何操作。当方法实现仅使用 t 类型的一个值时,这种方法效果最佳,因为您可以直接使用开关防护中的变量 (v := any(vec[a]).(type))。当您在开关防护中的值旁边有更多 t 值时,它就不再漂亮了,因为您必须单独转换和断言所有这些值:

func (vec vec[t]) less(a, b int) bool {
    switch v := any(vec[a]).(type) {
    case int64:
        return v < any(vec[b]).(int64)

    case time.time:
        return v.before(any(vec[b]).(time.time))

    // more cases...
    }
    return false
}

使用方法

参数化包含方法的接口并将其 t 限制为支持的类型。然后将 vector 的类型参数约束为两者。 这样做的优点是确保 vector 无法使用您忘记实现 less(t) bool 的类型进行实例化,并摆脱类型断言,否则可能会在运行时出现恐慌。

type lesser[t supportedtype] interface {
    less(t) bool
}

type vec[t interface { supportedtype; lesser[t] }] []t

func (vec vec[t]) less(a, b int) bool {
    return vec[a].less(vec[b])
}

使用方法和预声明类型

不可能。考虑以下因素:

type supportedtypes interface {
    // exact predeclared types
    int | string
}

type lesser[t supportedtypes] interface {
    less(t) bool
}

约束 lesser 具有空类型集,因为 intstring 都不能有方法。所以在这里你又回到了“精确类型但没有方法”的情况。

具有近似类型 (~t)

将上面的约束更改为近似类型:

type supportedtypes interface {
    // approximate types
    ~int | ~string
}

type lesser[t supportedtypes] interface {
    less(t) bool
}

类型开关不是一个选项,因为 case ~int: 不合法。并且约束上存在方法会阻止您使用预先声明的类型进行实例化:

Vector[MyInt8]{} // ok when MyInt8 implements Lesser
Vector[int8]     // doesn't compile, int8 can't implement Lesser

所以我看到的选项是:

  • 强制客户端代码使用定义的类型,这在许多情况下可能就很好
  • 将约束范围缩小到支持相同操作的类型
  • 反射(衡量性能损失是否对您来说太大的基准),但反射实际上无法找到底层类型,因此您只能使用 reflect.kindcanconvert 进行一些修改。

当/如果 this proposal 通过时,这可能会改进并可能胜过其他选项。

到这里,我们也就讲完了《在 go (1.18) 中对泛型进行多态实现的最佳方法是什么?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>