关于嵌入的问题

时间:2017-04-03 13:34:22

标签: go interface packages embedding

我在构建项目的主要类型时遇到了问题:描述符及其相应的视图(type View map[string]Descriptor)。

有几个子算法都使用View,但他们想要将数据添加到基础描述符,即向View添加方法。

假设我有一个基础包A和一个子包B,使用以下代码:

package A

// A.Descriptor only takes care in a Descriptor's address
type Descriptor interface {
    GetAddr() string
}

// Are the names OK?
// I thought of "Describer" for interface name and "Descriptor" for the struct
// But is not that better than Descriptor/BaseDescriptor    
type BaseDescriptor struct {
    Addr string
}
func (d BaseDescriptor) GetAddr() string { return d.Addr }

type View map[string]Descriptor

// A.View implements basic set functionality like Add, Remove, Union...
func (v *View) Add(descs... Descriptor) {
    for _, d := range descs {
        (*v)[d.GetAddr()] = item
    }
}

在另一个包中:

package B

import (
    "my_project/A"
)

// This package needs an "age" integer associated with each Descriptor
type Descriptor struct {
    gossip.BaseDescriptor

    age int
}

// Now, I want a new version of View with the ability to increment
// its Descriptors' age
func (v *NewView) IncrementAge() {
    for key, val := range *v {
        // If NewView directly handles B.Descriptor *struct*:
        (*v)[key].age += 1
        // Else, I could implement a
        // "func (d Descriptor) IncrementAge() Descriptor" to do so:
        (*v)[key] = val.IncrementAge()
    }
}

// But how should I define NewView?

我一直在墙上敲我的头听Rob Pike告诉我接口比大接口要好得多。但是现在我处理Descriptor,曾经是一个更大的“一体化”界面,我真的无法弄清楚如何将它拆分。所以欢迎任何建议!

基本上,我的目标是能够围绕我的不同子算法传递相同的Descriptor结构,最终描述符是A.Descriptor,B.Descriptor等的嵌入。每个嵌入都添加了一些功能。

0 个答案:

没有答案