【问题标题】:Embed two structs with the same name in a struct在一个结构中嵌入两个同名结构
【发布时间】:2017-06-16 12:16:25
【问题描述】:

如何在一个结构中嵌入两种同名的类型?例如:

type datastore {
    *sql.Store
    *file.Store
}

结果为@​​987654322@。我知道这是有道理的,因为您无法引用嵌入字段ds.Store,但是您如何实现这一点?

为了澄清,我想用datastore 实现一个接口。为此,两个结构都是必需的,因为它们的方法相互补充以创建接口。我有什么选择?

【问题讨论】:

  • 能否请您详细说明一下这些嵌入式结构的方法是如何相互补充的?

标签: inheritance go struct interface


【解决方案1】:

您可以尝试首先将您的 whatever.Store 包装成不同名称的类型:

import (
    "os"
    "whatever/sql"
)

type SqlStore struct {
    *sql.Store
}

type FileStore struct {
     *os.File
}

type DataStore struct {
     SqlStore
     FileStore
}

Playground link.

请注意,Go 1.9 可能会获得对类型别名的支持:请参阅 thisthis。我不确定这会对您的情况有所帮助,但可能会很有趣。

【讨论】:

    【解决方案2】:

    您确实可以引用一个字段,即使该字段存在于作为匿名字段包含的两个不同子结构中:

    package main
    
    import "fmt"
    
    type A struct {
        x int32
    }
    
    type B struct {
        x int32
    }
    
    type C struct {
        A
        B
    }
    
    func main() {
        c := C{A{1}, B{2}}
        //fmt.Println(c.x) // Error, ambiguous
        fmt.Println(c.A.x) // Ok, 1
        fmt.Println(c.B.x) // Ok, 2
    }
    

    【讨论】:

      【解决方案3】:

      使用type alias,例如:

      type sqlStore = sql.Store // this is a type alias
      
      type datastore {
          *sqlStore
          *file.Store
      }
      

      类型别名不会创建不同于创建它的类型的新的不同类型。它只是为sql.Store 表示的类型引入了一个别名sqlStore,这是另一种拼写。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-17
        • 1970-01-01
        • 2020-04-18
        • 2019-08-24
        • 1970-01-01
        • 1970-01-01
        • 2015-02-23
        相关资源
        最近更新 更多