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

What is the best way to have polymorphic implementations on a generic in go (1.18)?

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

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 那么我希望所有假值都在真值之前。

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


对所有具有相同功能的类型使用类型联合是行不通的 (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 号是最好的。

就我个人而言,我认为最好不要在联合中包含许多彼此无关的类型,因为它们不会共享许多通用操作,并且您最终会编写 type-specific 代码。那么使用泛型的意义何在...?

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

只有精确类型,没有方法

T 和 运行 上使用类型开关,任何对具体类型有意义的操作。当方法实现仅使用一个 T 类型的值时,这种方法效果最好,因为您可以直接使用 switch guard (v := any(vec[a]).(type)) 中的变量。当你在 switch guard 中的值旁边有更多 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

所以我看到的选项是:

  • 强制客户端代码使用定义的类型,在许多情况下这可能很好
  • 将约束的范围缩小到支持相同操作的类型[​​=74=]
  • 反射(用于查看性能损失是否对您来说太大的基准),但反射实际上无法找到底层类型,因此您只能使用 reflect.KindCanConvert.

这可能会改进并可能胜过其他选项 when/if this proposal 来了。