Go - 将具有相同嵌入式结构的结构存储在列表中

我有多个具有相同嵌入式结构的结构。在其中一个结构中,我想存储嵌入基结构的任何结构的列表。这是一个展示案例的小片段。


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


冉冉说
浏览 140回答 3
3回答

拉莫斯之舞

重要的是相同的界面:package mainimport (    "fmt")type Item interface{    fmt.Stringer}type ItemA struct {}func (a ItemA) String() string {    return "item A"}type ItemB struct {}func (a ItemB) String() string {    return "item B"}func main() {    items := make([]Item, 0)    items = append(items, ItemA{}, ItemB{})    fmt.Printf("Items: %v", items)}

倚天杖

您似乎期待的是.Go 不支持非接口类型的动态绑定。因此,您可以使用接口subtype polymorphismpackage mainfunc main(){    var bar Bar    var foo Foo    foo.Symbols = append(foo.Symbols, bar)}type Symbol interface {    Symbol()}type Base struct {    a int32}func (b Base)Symbol(){}type Foo struct {    Base    b int32    Symbols []Symbol}type Bar struct {    Base    c int32}或者,如果您不喜欢使用界面,则可以使用如下所示的技巧来反映。package mainimport "fmt"func main(){    var bar Bar    var foo Foo    err := foo.AddSymbol(bar)    if err != nil{        fmt.Println(err)    }}type Base struct {    a int32}func (b Base)Symbol(){}type Foo struct {    Base    b int32    symbol []interface{} // field made private}// AddSymbol : helper to append valuesfunc (f *Foo)AddSymbol(in interface{})(err error){    if f.symbol == nil{        f.symbol = make([]interface{},0)    }    switch typ := in.(type) {    case Base,Bar,Foo:        f.symbol = append(f.symbol,in)    default:        return fmt.Errorf("provided type: %s is not supported",typ)    }    return nil}type Bar struct {    Base    c int32}

慕丝7291255

我做了一些搜索和阅读。我想要实现的目标需要所谓的“总和类型”。目前 Go 不支持总和类型。但是,很少有替代方法来模拟求和类型的行为。它们在这里得到了很好的描述 Go 中求和类型的替代方案。更重要的是,看起来总和类型可能会在Go 2中得到支持。进一步阅读建议:规范:添加总和类型/可区分的并集,规范:泛型:使用类型集删除约束中的类型关键字。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go