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。
在操场上玩
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下