【问题标题】:Go generics: is it possible to embed generic structs?Go generics:是否可以嵌入泛型结构?
【发布时间】:2021-02-09 12:20:02
【问题描述】:

我正在写我的硕士论文,我正在间接使用 Go (go2go) 中的泛型“原型”。

我想知道是否可以使用组合并嵌入通用结构(当然是 go2go)?

我想做这样的事情:

type A[T any] struct {
    a T
}

func (a A[T]) F() T {
    return a.a
}

type B[T any] struct {
    A[T]
}

func main() {
    b := B[string]{A[string]{"Hello"}}
    fmt.Println(b.F())
}

我会收到此错误消息,它指的是在主函数中调用“Println”:“b 的类型 B[string] 与 A[T] 不匹配(无法推断 T)”

这个的非通用版本可能是这样的(它可以工作并打印“Hello”):

type A struct {
    a string
}

func (a A) F() string {
    return a.a
}

type B struct {
    A
}

func main() {
    b := B{A{"Hello"}}
    fmt.Println(b.F())
}

我对 Go 中这个新的通用方面不是很熟悉,所以可能是我做错了?还是不可能?

【问题讨论】:

    标签: go generics struct


    【解决方案1】:

    是的,可以在您提供的表单中嵌入一个通用结构

    // type-parametrized struct
    type A[T any] struct {
        a T
    }
    
    type B[T any] struct {
        A[T] // embedded
    }
    

    您的代码 sn-p 在 GoTip playground 上运行良好,与旧的 Playground 不同,它与 Go master 分支保持同步。 (Anyway Go 1.18 已经发布了测试版)。

    请注意,在所有情况下,A 都必须使用类型实例化,无论是在结构中还是在变量声明中:

    type B[T any] struct {
        A // cannot use generic type A[T any] without instantiation
    }
    

    最后,类型参数不必从嵌入结构继承。因此

    type C[T any] struct {
        A[string] // fine
    }
    
    type D struct {
        A[string] // fine
    }
    

    在这种情况下,当实例化CD 类型的变量时,必须使用相同的类型参数初始化字段A

    c := D{A[string]{"Hello"}}
    

    不可能直接嵌入类型参数:

    type A[T any] struct {
        T // embedded type param
    }
    

    当前的泛型提案does say认为这应该是可能的:

    当泛型类型是结构体,并且类型参数作为字段嵌入到结构体中时,字段的名称就是类型参数的名称。

    但是决定将其排除在 Go 1.18 之外 (Source)。

    【讨论】:

      【解决方案2】:

      go2go 游乐场是一个实验性的东西。它不支持所有有效的通用程序。

      https://github.com/golang/go/issues/44689,好像类型嵌入有问题。

      没有错误/缺陷的主要实现将在稍后推出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多