How to declare multiple interface constraints in golang?

huangapple go评论92阅读模式
英文:

How to declare multiple interface constraints in golang?

问题

假设我有两个接口:

interface A {...}
interface B {...}

现在我想定义一个函数来接受同时实现接口A和B的参数:

func test(param A & B) {...} // 有类似的语法吗?

我不想每次都写一个新的接口来嵌入其他接口,以便引用多个接口,像这样:

interface C {
  A
  B
}
func test(param C) {...} // 对于两个接口可以,那么对于3个、4个甚至9个接口呢?

我不知道如何在Go语言中表示交集类型,有什么想法吗?

英文:

Suppose I have two interfaces:

interface A {...}
interface B {...}

Now I want to define a function to accept some param of interface A & B(i.e., param implements both interface A and B):

func test(param A & B) {...} // any similar syntax?

I don't want to write a new interface to embed other interfaces every time I want to refer to multiple interfaces like this:

interface C {
  A
  B
}
func test(param C) {...} //ok with 2 interfaces, what about 3, 4 or even 9?

I don't know how to express intersection type in golang, any ideas?

答案1

得分: 1

在Go语言中,这是不可能的,因为它是一种Go语言设计时避免的晦涩控制流。

类型不需要按名称实现接口,所以我的建议是为每个参数声明匿名接口,其中只包含你知道该函数需要的方法。

英文:

Not possible in go as it is an obscure control flow that Go is designed to avoid.

Types aren't required to implement interfaces by name so my recommendation is to declare anonymous interfaces for each argument containing only the methods you know this function requires.

huangapple
  • 本文由 发表于 2023年3月26日 20:16:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75847693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定