英文:
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
嵌入A
在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
但是,没有字段的接口。只有方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论