分享
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
package main
import "fmt"
type gameObject struct {
name string
test
}
type test struct {
v string
}
func (o *test) Val() {
fmt.Printf("test %s \n", o.v)
}
func (o *test) Attack() {
fmt.Printf("test Attack %s \n", o.v)
}
func (o *gameObject) Name() string {
return o.name
}
func (o *gameObject) Attack() {
fmt.Printf("GameObject %s do not know how to attack\n", o.name)
}
type player struct {
gameObject
}
func (p *player) Attack() {
fmt.Printf("player %s attacks\n", p.name)
}
type monster struct {
gameObject
}
type challenger interface {
Name() string
Attack()
}
func main() {
p := &player{gameObject: gameObject{name: "devgl", test: test{v: "xxx"}}}
m := &monster{gameObject: gameObject{name: "slime", test: test{v: "xxx2"}}}
Attack(p)
Attack(m)
m.Attack()
m.Val()
m.gameObject.test.Val()
m.gameObject.test.Attack()
}
func Attack(c challenger) {
c.Attack()
}
代码运行结果:
player devgl attacks
GameObject slime do not know how to attack
GameObject slime do not know how to attack
test xxx2
test xxx2
test Attack xxx2
用struct来声明一个结构体
总结:
对于多层嵌套得 struct:
内层struct属性会"嵌入"(embed,继承)到外层;
外层struct属性会覆盖内层struct的相同属性;
struct之间有层级关系;
有疑问加站长微信联系(非本文作者))
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1396 次点击
上一篇:切片为空和空切片等同
下一篇:golang 学习所遇问题
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传