inheritance - GoLang equivalent for inheritence using interface with data and member functions -


i golang newbie pardon me if there obvious missing. have following structures:

type base interface {     func1()     func2()     common_func() }  type derived1 struct {     base // anonymous meaning inheritence     data datumtype }  type derived2 struct {     base // anonymous meaning inheritence     data datumtype } 

now want following:

  1. keep 'data datumtype' base in way looking @ definition of base 1 can know data common structs.
    1. implement common_func() in 1 place derived structs don't need it.

i tried implementing function interface fails compilation. tried create struct , inherit not finding ways that. there clean way out ?

go not have inheritance. instead offers concept of embedding.

in case don't need/want define base interface. make struct , define functions methods. embedding base in derived structs give them methods.

type base struct{     data datumtype      } func (b base) func1(){  }  func (b base) func2(){  }  func (b base) common_func(){  }  type derived1 struct {     base // anonymous meaning embedding }  type derived2 struct {     base // anonymous meaning embedding } 

now can do:

d := derived1{} d.func1() d.func2() d.common_func() 

and (as pointed out david budworth in comment) can access fields of base referring it's type name so:

d.base.data = 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -