我有多个具有相同嵌入式结构的结构。在其中一个结构中,我想存储嵌入基结构的任何结构的列表。这是一个展示案例的小片段。
package main
type Symbol interface{}
type Base struct {
a int32
}
type Foo struct {
Base
b int32
Symbols []Base
// Below works
// Symbols []Symbol
}
type Bar struct {
Base
c int32
}
func main () {
var bar Bar
var foo Foo
foo.Symbols = append(foo.Symbols, bar)
}
但是,这不起作用。我得到.当我使用空界面时,一切都正常。但是,这种方法完全绕过了类型系统,因为现在所有内容都可以存储在列表中。我想以某种方式表示只有 ,并且可以存储在列表中,以便编译器可以检查是否满足此要求。我的结构没有任何方法,肯定不是那些共享行为并且可以添加到界面中的方法。在接口和虚拟实现中添加一些虚拟方法似乎非常人为。处理此类情况的Go惯用方法是什么?./main.go:25:22: cannot use bar (type Bar) as type Base in appendSymbolBaseFooBar
冉冉说
拉莫斯之舞
倚天杖
慕丝7291255
随时随地看视频慕课网APP
相关分类