有沒有一種方法可以確定具體類型實現從一個 任意接口列表的接口?我知道一個類型開關,但我想知道所有滿意的 接口。哪些接口滿足任意接口列表?
例如,給定:
type Mover interface { Move() }
type Talker interface { Talk() }
type Flyer interface { Fly() }
type Person struct{}
func (a *Person) Move() {fmt.Println("Moving...") }
func (a *Person) Talk() {fmt.Println("Talking...") }
我可以手動測試每個接口如下:
func testInterfaces(entity interface{}) {
_, ok := entity.(Mover)
if ok {
fmt.Println("mover")
}
_, ok := entity.(Talker)
if ok {
fmt.Println("talker")
}
_, ok := entity.(Flyer)
if ok {
fmt.Println("flyer")
}
}
一個人值, 「動子」 和 「講話者」 將打印。但是,我寧願有這樣的(非工作)的功能之一:
func testInterfaces2(entity interface{}, interfaceList type??) {
for _, inter := range interfaceList {
val, ok := entity.(inter)
if ok {
// do something with val
}
}
}
有沒有一種方法,我可以實現這樣的僞功能,也許通過反映包或其他方式?
我m不確定,所以我不會發表答案,但我認爲在運行時通過比較檢查接口,沒有滿意接口的主列表。沒有這種事情的一個潛在原因可能允許編譯器優化未使用的接口數據。我懷疑你所要求的不存在,並且不太可能被添加。 – LinearZoetrope