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\n",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\n",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\n",s)
}
//运行结果:
main.Student{Score:200, Name:"abc", Age:100, People:main.People{Name:"def", Age:20}}

  

 

转载于:https://www.cnblogs.com/wanghaijun999/p/8157092.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值