zoukankan      html  css  js  c++  java
  • 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}}
    

      

  • 相关阅读:
    岛田庄司《占星术杀人魔法》读后感
    OutputCache祥解
    ZOJ Monthly, June 2014 月赛BCDEFGH题题解
    接口和抽象类有什么差别
    C语言指针的初始化和赋值
    深入探讨this指针
    郁 繁体为“鬰” 古同 “鬱”
    socketpair的使用
    Android的FrameLayout使用要注意的问题
    下确界和上确界
  • 原文地址:https://www.cnblogs.com/wanghaijun999/p/8157092.html
Copyright © 2011-2022 走看看