1 回答

TA貢獻1801條經驗 獲得超16個贊
定義一個具有公共字段的結構,并使其實現一個接口,該接口表明它能夠使公共字段無效。然后將此結構嵌入到應該能夠使字段無效的其他結構類型中。
// 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 關注
- 137 瀏覽
添加回答
舉報