go 语言 struct 另类构造函数 继承

1. go 中struct 没有构造函数,但是可以使用另一种方式来构造。

type School struct {
	Name string
	Addr string
}

func NewSchool(name, addr string) *School {
	return &School {
		Name:name,
		Addr:addr,
	}
}
func testNewSchool(){
	s1:= NewSchool("清华大学","北京海淀") //生成实例
	fmt.Println(*s1)
}
func main() {
    testNewSchool()
}
//运行结果
{清华大学 北京海淀}

  2.匿名函数实现继承

type People struct{
	Name string
	Age int
}
type Student struct {
	Score int
	People
}
func test1(){
	var s Student
	s.Name = "abc"
	s.Age = 100
	s.Score = 200
	fmt.Printf("%#v
",s)
}
//运行结果
main.Student{Score:200, People:main.People{Name:"abc", Age:100}}

  上面可以看出s相当于继承了People的 Name 和Age属性

如果Student有Name和Age属性呢?

type People struct{
	Name string
	Age int
}
type Student struct {
	Score int
	Name string
	Age int
	People
}
func test1(){
	var s Student
	s.Name = "abc"
	s.Age = 100
	s.Score = 200
	fmt.Printf("%#v
",s)
}
//运行结果 main.Student{Score:200, Name:"abc", Age:100, People:main.People{Name:"", Age:0}}

  从上面输出结果可以看出,自己的属性覆盖了继承的属性,如果给匿名字段属性赋值呢?

type People struct{
	Name string
	Age int
}
type Student struct {
	Score int
	Name string
	Age int
	People
}
func test1(){
	var s Student
	s.Name = "abc"
	s.Age = 100
	s.Score = 200
	s.People.Name = "def"
	s.People.Age = 20
	fmt.Printf("%#v
",s)
}
//运行结果:
main.Student{Score:200, Name:"abc", Age:100, People:main.People{Name:"def", Age:20}}

  

原文地址:https://www.cnblogs.com/wanghaijun999/p/8157092.html