Go - 如何处理结构类型之间的公共字段

Mat*_*w H 6 struct types go

如果我有两种类型:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现以下,而不需要两个方法,因为两者都访问相同名称的字段并返回它们的总和?

func (a *A) Sum() int {
     return a.X + a.Y
}

func (b *B) Sum() int {
     return b.X + b.Y
}
Run Code Online (Sandbox Code Playgroud)

当然,有X和Y方法,我可以定义一个包含这两种方法的接口.字段有模拟吗?

the*_*tem 11

嵌入AB.

type A struct {
      X int
      Y int
}

func (a *A) Sum() int {
     return a.X + a.Y
}

type B struct {
      *A
      Z int 
}

a := &A{1,2}
b := &B{&A{3,4},5}

fmt.Println(a.Sum(), b.Sum()) // 3 7
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/fjT9c-m_Lj

但不,没有领域的界面.只有方法.