Go 组合和嵌入

示例

组合提供了继承的替代方法。结构可以在其声明中包含其他名称:

type Request struct {
    Resource string
}

type AuthenticatedRequest struct {
    Request
    Username, Password string
}

在上面的例子中,AuthenticatedRequest将包含四个公共成员:Resource,Request,Username,和Password。

可以实例化复合结构,并使用与普通结构相同的方法:

func main() {
    ar := new(AuthenticatedRequest)
   ar.Resource= "example.com/request"
   ar.Username= "bob"
   ar.Password= "P@ssw0rd"
    fmt.Printf("%#v", ar)
}

在操场上玩

嵌入

在前面的示例中,Request是一个嵌入式字段。组成也可以通过嵌入其他类型来实现。例如,这对于装饰Struct具有更多功能很有用。例如,继续参考Resource示例,我们需要一个函数来格式化Resource字段的内容,并以http://或作为前缀https://。我们有两个选择:在AuthenticatedRequest上创建新方法或从其他结构嵌入它:

type ResourceFormatter struct {}

func(r *ResourceFormatter) FormatHTTP(resource string) string {
    return fmt.Sprintf("http://%s", resource)
}
func(r *ResourceFormatter) FormatHTTPS(resource string) string {
    return fmt.Sprintf("https://%s", resource)
}


type AuthenticatedRequest struct {
    Request
    Username, Password string
    ResourceFormatter
}

现在,主要功能可以执行以下操作:

func main() {
    ar := new(AuthenticatedRequest)
   ar.Resource= "www.example.com/request"
   ar.Username= "bob"
   ar.Password= "P@ssw0rd"

    println(ar.FormatHTTP(ar.Resource))
    println(ar.FormatHTTPS(ar.Resource))

    fmt.Printf("%#v", ar)
}

看一下AuthenticatedRequest具有ResourceFormatter嵌入式结构的。

但是它的缺点是您不能访问合成之外的对象。因此ResourceFormatter无法从访问成员AuthenticatedRequest。

在操场上玩