I am a beginner in Go. I maybe thinking too traditional coming from years in other languages, but here is what I want to do in Go. Assume the following use case
Doable in Go?
The short answer is: No, that is not doable
Go is a strictly typed language. This allows the linker to leave out type definitions, methods and functions not used by the application.
That means, unless a type (such as struct A) are referenced and used somewhere, it will be omitted.
But in your comment, you mentioned you don't want the types but rather the currently existing instances of any type that implements the interface.
This is not possible either.
Alternative
My suggestion is to create a global map (or slice):
var instMap = map[string]StartStopper
And have each struct add an instance to that map with an init function that will automatically be called at the start of the application:
type A struct {}
func init() {
instMap["A"] = new(A)
}
Then when you want to start all the instances, just iterate over the map and call Start()
Edit
And if it is not a one-instance-per-type situation but rather multiple instances for each type, then you will have to add to the map (or slice) whenever a new instance is created. And you would have to remember deleting the instance from the map when it is not to be used anymore, or else it won't be handled by the Garbage Collector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With