继承是面向对象软件技术当中的一个概念,与多态、封装共为面向对象的三个基本特征。继承可以使得子类具有父类的属性和方法或者重新定义、追加属性和方法等。
但在go语言中并没继承的概念,只能通过组合来实现继承。组合就是通过对现有对象的拼装从而获得实现更为复杂的行为的方法。
type Animal struct {
}
//继承
type Cat struct {
//匿名
*Animail
}
//组合
type Dog struct {
animal Animal
}
package main
import "fmt"
type Student struct {
Person // 匿名字段,只有类型,没有成员的名字
score float64
}
type Teacher struct {
Person
salary float64
}
type Person struct {
id int
name string
age int
}
func main() {
//var stu Student=Student{Person{100,"愚公",31},90}
// 部分初始化
// var stu Student=Student{score:100}
var stu Student = Student{Person: Person{id: 100}}
fmt.Println(stu)
//fmt.Println(stu1)
}
package main
import "fmt"
type Student struct {
*Person // 匿名字段
score float64
}
type Person struct {
id int
name string
age int
}
func main() {
var stu Student = Student{&Person{101, "愚公", 18}, 90}
fmt.Println(stu.name)
}
package main
import "fmt"
type Student struct {
Person
score float64
}
type Person struct {
id int
name string
age int
}
func main() {
var stu Student = Student{Person{101, "愚公1号", 18}, 90}
var stu1 Student = Student{Person{102, "愚公2号", 18}, 80}
stu.score = 100
fmt.Println("愚公一号考试成绩:", stu.score)
fmt.Println(stu1.score)
fmt.Println(stu1.Person.id)
fmt.Println(stu1.id)
}
package main
import "fmt"
type Student struct {
Person
score float64
}
type Person struct {
Object
name string
age int
}
type Object struct {
id int
}
func main() {
var stu Student
stu.age = 18
fmt.Println(stu.Person.age)
stu.id = 101
fmt.Println(stu.Person.Object.id)
}