I am experimenting to migrate a nodejs system (typescript) to golang. Its going well except i am having trouble in reproducing the following in idiomatic go
I have the following abstract class:
abstract class BaseSensor {
beforeStart() {/*default implementation*/ }
afterStart() {/*default implementation*/ }
shutdown() {/*default implementation*/ }
abstract process();
work() {
this.beforeStart()
//...
this.afterStart()
//...
this.process()
//...
this.shutdown()
}
}
then i have some concrete classes/sensors which implement atleast the process()
method and optionally any of the other lifecycle methods.
class SensorA extends BaseSensor {
process() {
//SensorA specific processing
}
}
class SensorB extends BaseSensor {
beforeStart() {
//SensorB overriding beforeStart()
}
process() {
//SensorB specific processing
}
}
SensorA
only implements the process()
method and doesn't override anything else. SensorB
implements process()
and also overrides beforeStart()
.
What is the correct way of doing something like this in golang
Top comments (4)
A quick thought says Inheritance is not really a game in Go, however it embraces EmbeddedTypes for something similar.
Roughly -
And then you can invoke them as follows -
Rahul already made the important part, I'd like to add code for Work()
then you can do something like following:
thanks
Hello!
Another way to do this is: play.golang.org/p/tmzumHEIo2H
Which does not use embedding or types implementing all the methods but rather functionals options and a default implementation; with the big caveat the concrete implementations are not sharing state in their methods: