2 回答
TA贡献1777条经验 获得超10个赞
看起来您只需要在其他结构中嵌入一个 Common 结构(有时称为 mixin)。
type Common struct {
ID string
Creator string
CreateOn time.Time
Edition int
}
type User struct {
Common
Name string
Password string
}
type Book struct {
Common
Name string
ISBN string
}
此外,我会将AutoFilled函数设为 Common 上的方法。(使用接口会失去类型安全性。)
func (c *Common)Autofill() {
// set fields on Common struct
}
func main() {
user := &User{}
user.Autofill()
TA贡献1797条经验 获得超6个赞
这是另一种方法。
对于每个结构(Book和User),创建一个名为 的方法New<StructName。举Book个例子
func NewBook() *Book {
return &Book {
//you can fill in default values here for common construct
}
}
您可以通过创建一个Common结构来进一步扩展此模式,并将该对象传递给NewBook您创建它时,即,
func NewBook(c Common) *Book {
return &Book {
Common: c
//other fields here if needed
}
}
现在在您的主代码中,您将执行此操作
func main() {
c := NewCommon() //this method can create common object with default values or can take in values and create common object with those
book := NewBook(c)
//now you don't need autofill method
fmt.Println("Thanks, playground")
}
- 2 回答
- 0 关注
- 136 浏览
添加回答
举报
