dtu15253 2017-06-08 14:53
浏览 51
已采纳

仅导出由嵌入式结构实现的方法子集

Is it possible to export only a subset of methods implemented by an embedded struct? Is this a very go-unlike way to reduce copy - and - pasting of code and there is a more idiomatic way to do this?

type A struct {
}

func (a *A) Hello() {
    fmt.Println("Hello!")
}

func (a *A) World() {
    fmt.Println("World!")
}

type B struct {
    A
}

type C struct {
    A
}

func main() {
    b := B{}
    c := C{}

    // B should only export the Hello - function
    b.Hello()

    // C should export both Hello - and World - function
    c.Hello()
    c.World()
}
  • 写回答

1条回答 默认 最新

  • dsf5632 2017-06-08 14:57
    关注

    This is how embedding works, there's nothing you can do about it. (Actually there is, see dirty trick at the end.)

    What you want may be achieved with interfaces though. Make your structs unexported, (B => b and C => c), and create "constructor" like functions, which return interface types, containing only the methods you wish to publish:

    type b struct {
        A
    }
    
    type c struct {
        A
    }
    
    type Helloer interface {
        Hello()
    }
    
    type HelloWorlder interface {
        Helloer
        World()
    }
    
    func NewB() Helloer {
        return &b{}
    }
    
    func NewC() HelloWorlder {
        return &c{}
    }
    

    You might want to call the interfaces and functions different, this is just for demonstration.

    Also note that while the returned Helloer interface does not include the World() method, it is still possible to "reach" it using type assertion, e.g.:

    h := NewB() // h is of type Helloer
    if hw, ok := h.(HelloWorlder); ok {
        hw.World() // This will succeed with the above implementations
    }
    

    Try this on the Go Playground.

    Dirty trick

    If a type embeds the type A, (fields and) methods of A that get promoted will become part of the method set of the embedder type (and thus become methods of type A). This is detailed in Spec: Struct types:

    A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

    The focus is on the promotion, for which the selector must be legal. Spec: Selectors describes how x.f is resolved:

    The following rules apply to selectors:

    1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

    [...]

    What does this mean? Simply by embedding, B.World will denote the B.A.World method as that is at the shallowest depth. But if we can achieve so that B.A.World won't be the shallowest, the type B won't have this World() method, because B.A.World won't get promoted.

    How can we achieve that? We may add a field with name World:

    type B struct {
        A
        World int
    }
    

    This B type (or rather *B) will not have a World() method, as B.World denotes the field and not B.A.World as the former is at the shallowest depth. Try this on the Go Playground.

    Again, this does not prevent anyone to explicitly refer to B.A.World(), so that method can be "reached" and called, all we achieved is that the type B or *B does not have a World() method.

    Another variant of this "dirty trick" is to exploit the end of the first rule: "If there is not exactly one f with shallowest depth". This can be achieved to also embed another type, another struct which also has a World field or method, e.g.:

    type hideWorld struct{ World int }
    
    type B struct {
        A
        hideWorld
    }
    

    Try this variant on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B