Go 多态 如何建表啊?

li_mingxie 2017-06-01 03:27:20

type Animal interface {
Sleep()
Age() int
Type() string
}
type Cat struct {
MaxAge int
Owner string
}

func (this *Cat) Sleep() {
fmt.Println("Cat need sleep")
}
func (this *Cat) Age() int {
return this.MaxAge
}
func (this *Cat) Type() string {
return this.Owner
}

/*=======================================================*/

type Dog struct {
MaxAge int
}

func (this *Dog) Sleep() {
fmt.Println("Dog need sleep")
}
func (this *Dog) Age() int {
return this.MaxAge
}
func (this *Dog) Type() string {
return "Dog"
}

这我如何建表啊?
以前用C# 有 Animal, Dog, Cat 3个表 而且MaxAge是抽象类的的字段。
Go 只能建Dog, Cat 两个表 各自包含着MaxAge吗?
...全文
1448 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
pirlo-san 2017-08-30
  • 打赏
  • 举报
回复
既然使用interface,说明这个类型就是一种抽象,不能被实例化的,也就不应该有成员
YY643523411 2017-06-15
  • 打赏
  • 举报
回复
可以再写一个Base结构体,Cat和Dog继承于它就可以了 type Base struct { MaxAge int } type Cat struct { Base Owner string } type Dog struct { Base }

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧