Go – 如何处理结构类型之间的共同字段

huangapple go评论84阅读模式
英文:

Go — how to handle common fields between struct types

问题

如果我有两种类型:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}

是否有办法在不需要两个方法的情况下实现以下功能,假设两者都访问具有相同名称的字段并返回它们的总和?

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

func (b *B) Sum() int {
     return b.X + b.Y
}

当然,如果X和Y是方法,我可以定义一个包含这两个方法的接口。是否有类似于字段的类比?

英文:

If I have two types:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}

Is there any way to achieve the following without needing two methods, given that both access identically-named fields and return the sum of them?

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

func (b *B) Sum() int {
     return b.X + b.Y
}

Of course, were X and Y methods, I could define an interface containing these two methods. Is there an analogue for fields?

答案1

得分: 13

嵌入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

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

但是,没有字段的接口。只有方法。

英文:

Embed A in B.

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

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

But no, there's no interface for fields. Only methods.

huangapple
  • 本文由 发表于 2013年3月4日 09:13:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/15193030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定