1 回答
TA贡献1801条经验 获得超15个赞
定义一个具有公共字段的结构,并使其实现一个接口,该接口表明它能够使公共字段无效。然后将此结构嵌入到应该能够使字段无效的其他结构类型中。
// CommonNullifier is able to nullify its common field(s)
type CommonNullifier interface {
NullifyCommon()
}
// StructCommon contains the common struct fields
type StructCommon struct {
Common string
}
func (sc *StructCommon) NullifyCommon() {
sc.Common = ""
}
// Struct1 embeds common fields, thus implements CommonNullifier
type Struct1 struct {
StructCommon
Foo string
}
// Struct2 also embeds common fields, thus also implements CommonNullifier
type Struct2 struct {
StructCommon
Bar string
}
// NullifyCommon nullfies the 'common' fields in the argument
func NullifyCommon(s CommonNullifier) {
s.NullifyCommon()
}
您也可以使用反射,但使用接口通常更具可读性。
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报