在下面的示例中,我试图定义一个PreciseAdder类型来简化实例化泛型类型的使用. 不幸的是,Go编译器似乎认为泛型类型上定义的方法不适用于PreciseAdder类型.我知道我可以通过组合解决这个问题,但是有没有一种方法可以用类型定义来解决这个问题?如果没有,原因是什么?

package main

type Addable interface {
    Add()
}

type Adder[T Addable] struct{}

func (a Adder[T]) DoAdd(){}

type PreciseAddable struct{}

func (p PreciseAddable)Add(){}

type PreciseAdder Adder[PreciseAddable]

func main() {
    var p PreciseAdder
    p.DoAdd()
}

推荐答案

这一点:

type PreciseAdder Adder[PreciseAddable]

type declaration,更确切地说是type definition.它创建了一个新类型,所有方法都被剥离.

而不是使用type alias,它将保留所有方法,它只是引入了一个新的标识符来引用相同的类型:

type PreciseAdder = Adder[PreciseAddable]

(请注意标识符和类型之间的=号.)

Go相关问答推荐

杜松子wine -戈尼克背景在 children 围棋例行公事中被取消

Golang测试容器,无法使网络正常工作

允许在 struct 中使用复合作为函数参数

为什么要立即调用内联函数,而不仅仅是调用其包含的函数?

Go:为什么我不能比较 net.Addr

如何绕过深层 xml,没有嵌套循环?

通过 Terraform 中的 MapNestedAtribute 进行迭代

在golang中以JSON格式获取xwwwformurlencoded请求的嵌套键值对

如何使用 sync.WaitGroup 来执行所有的 goroutine?

从 eBPF LRU 哈希映射中错误驱逐的元素

如何在 `hashicorp / terraform-exec` 中将 `ApplyConfig` 传递给 `tf.Apply()`?

如何将 base64 编码的公钥转换为 crypto.PublicKey 或 ecdsa.PublicKey

Go 信号处理程序不处理终端窗口关闭

使用 `didip/tollbooth` 限制每小时最大请求数

panic :拨号 tcp:在 172.22.64.1:53 上查找 bookstoreDB:没有这样的主机

如何在 GORM 中迭代一个 int 数组

每 N 秒运行一次函数,上下文超时

Go Fyne 禁用 HSplit 调整大小?

如何在 Unmarshal 中使用泛型(转到 1.18)

Golang 查询扫描未将查询正确扫描到 struct 中