Go学习笔记-面向对象struct之继承
source link: https://studygolang.com/articles/25760
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
前一篇说了基于 struct
的 method
实现,现在我们来看下 struct
中的 method
继承。
//定义一个person类型 type Person struct { Name string Age int Sex string } //获取person的年龄 func (Person *Person)getAge() int { return Person.Age } //获取person的性别 func (Person *Person)getSex() string { return Person.Sex } //定义一个Worker类型 type Worker struct { Person Job string Age int } //获取Worker的年龄 func (Worker *Worker)getAge() int { return Worker.Age } func main() { Person := Person{"andy",9,"男"} andy := Worker{Person,"搬砖工",3} fmt.Printf("%s:%s,职业:%s,年龄:%d,工龄:%d\r\n",andy.Name,andy.Sex,andy.Job,andy.Person.getAge(),andy.getAge()) //andy:男,职业:搬砖工,年龄:9,工龄:3 }
上面这个示例,我们首先定义一个 person
类型。然后定义了一个 worker
类型,继承了 person
。但是对于 worker
又希望有自己的 age
属性,与 getAge
方法。那么这个时候我们可以重写 person
的属性与方法。但是在使用的时候,如果我们想要使用 person
中已经被 worker
重写的方法或者属性,我们就需要指定到 person
,比如 andy.Person.getAge()
。这样直接告诉程序,我们需要取得 person
中的 getAge
方法。
期待一起交流
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK