mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-22 23:12:15 +08:00
docs: 结构体继承
This commit is contained in:
parent
c96b7cebe0
commit
03faf47f2d
36
base/struct/inheritance/main.go
Normal file
36
base/struct/inheritance/main.go
Normal file
@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 结构体 实现 类似 其他语言的 继承
|
||||
|
||||
// Animal 动物
|
||||
type Animal struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
func (a *Animal) Move() {
|
||||
fmt.Printf("%s: 移动\n", a.Name)
|
||||
}
|
||||
|
||||
// Dog 狗
|
||||
type Dog struct {
|
||||
Animal // Animal 拥有的方法, Dog 也拥有
|
||||
Feet uint8
|
||||
}
|
||||
|
||||
func (d *Dog) Cell() {
|
||||
fmt.Printf("%s: 叫\n", d.Name)
|
||||
}
|
||||
|
||||
func main() {
|
||||
d1 := &Dog{
|
||||
Animal: Animal{Name: "大黄"},
|
||||
Feet: 4,
|
||||
}
|
||||
|
||||
fmt.Printf("%#v\n", d1)
|
||||
//d1.Animal.Move()
|
||||
d1.Move()
|
||||
d1.Cell()
|
||||
}
|
Loading…
Reference in New Issue
Block a user