oop - How to implement an abstract class in Go? -


how implement abstract class in go? go doesn't allow have fields in interfaces, stateless object. so, in other words, possible have kind of default implementation method in go?

consider example:

type daemon interface {     start(time.duration)     dowork() }  func (daemon *daemon) start(duration time.duration) {     ticker := time.newticker(duration)      // call daemon.dowork() periodically       go func() {         {             <- ticker.c             daemon.dowork()         }     }() }  type concretedaemona struct { foo int } type concretedaemonb struct { bar int }  func (daemon *concretedaemona) dowork() {     daemon.foo++     fmt.println("a: ", daemon.foo) }  func (daemon *concretedaemonb) dowork() {     daemon.bar--     fmt.println("b: ", daemon.bar) }  func main() {     da := new(concretedaemona)     db := new(concretedaemonb)      start(da, 1 * time.second)     start(db, 5 * time.second)      time.sleep(100 * time.second) } 

this won't compile it's not possible use interface receiver.

in fact, have answered question (see answer below). however, idiomatic way implement such logic? there reasons not have default implementation besides language's simplicity?

an easy solution move daemon *daemon argument list (thus removing start(...) interface):

type daemon interface {     // start(time.duration)     dowork() }  func start(daemon daemon, duration time.duration) { ... }  func main() {     ...     start(da, 1 * time.second)     start(db, 5 * time.second)     ... } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -