Does Go support Inheritence? -
i have heard lot of people talk go, , how not support inheritance. until using language, went along crowd , listened hear say. after little messing language, getting grips basics. came across scenario:
package main type thing struct { name string age int } type uglyperson struct { person wonkyteeth bool } type person struct { thing } type cat struct { thing } func (this *cat) setage(age int){ this.thing.setage(age) } func (this *cat getage(){ return this.thing.getage() * 7 } func (this *uglyperson) getwonkyteeth() bool { return this.wonkyteeth } func (this *uglyperson) setwonkyteeth(wonkyteeth bool) { this.wonkyteeth = wonkyteeth } func (this *thing) getage() int { return this.age } func (this *thing) getname() string { return this.name } func (this *thing) setage(age int) { this.age = age } func (this *thing) setname(name string) { this.name = name }
now, composes person , cat structs, thing struct. doing so, not person , cat struct share same fields thing struct, also, through composition, methods of thing shared. not inheritance? implenting interface such:
type thing interface { getname() string setname(name string) setage(age int) }
all 3 structs joined or should say, can used in homogenous fashion, such array of "thing".
so, lay on you, not inheritance?
edit
added new derived struct called "ugly person" , overridden setage method cat.
it inheritance not sort of inheritance after. example promising b/c person
, cat
behaviorally , structurally equal each other modulo type names.
as you'd attempt use "inheritance" 'extend' base type with, example added fields, you'll find receiver of "base class" base class, never extended one. iow, cannot achieve structurally polymorphous type hierarchy.
otoh, go supports purely behavioral inheritance via interfaces. embedding 1 interface does create inheritance tree.
package main import "fmt" type thing struct { name string age int } func (t *thing) me() { fmt.printf("i %t.\n", t) } type person struct { thing } func (p *person) iam() { fmt.printf("i %t.\n", p) } type cat struct { thing } func (c *cat) iam() { fmt.printf("i %t.\n", c) } func main() { var p person var c cat p.me() p.iam() c.me() c.iam() }
Comments
Post a Comment