go - 将接口(interface)方法的参数限制为一些允许的结构?

标签 go generics methods

假设我有一个界面:

type Module interface {
    Run(moduleInput x) error // x is the type of moduleInput
}

其中每个“模块”将实现Run功能。但是,moduleInput 不是单个结构 - 它应该能够接受任何结构,但只能接受允许的结构,即不是 interface{} (例如,仅 moduleAInputsmoduleBInputs 结构)。

理想情况下,每个模块的 Run 函数的类型为 moduleXInput,其中 X 是示例模块。

是否可以使用泛型或其他方式约束 moduleInput 的类型?

最佳答案

使用通用接口(interface),限制为您想要限制的类型的联合:

// interface constraint
type Inputs interface {
    moduleAInputs | moduleBInputs
}

// parametrized interface
type Module[T Inputs] interface {
    Run(moduleInput T) error
}

请注意,接口(interface) Module[T] 现在可以通过其方法与该接口(interface)的实例化相匹配的类型来实现。有关此内容的全面解释,请参阅:How to implement generic interfaces?

关于go - 将接口(interface)方法的参数限制为一些允许的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72989975/

相关文章:

.net - IEnumerator<T>.Current 和 IEnumerator.Current 之间的关系以及为什么 IEnumerator<T> 实现 IDisposable

java - Java 中类型删除后具有相同签名的静态方法

c# - 如何在 C# 中访问 protected 方法

javascript - 返回数组中的特定对象值

algorithm - Golang指向 slice 的指针

Golang Google Drive Oauth2 不返回刷新 token

go - 我可以创建一个与另一个签名相同的函数吗?

java - 如何重载泛型构造函数

java - 移动数组中元素的方法

sockets - 去: socket library to get hostname