Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - Scan for all structs of type something

Tags:

reflection

go

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

  1. I have interface I. This interface has functions, start() and stop()
  2. There are many structs implementing the interface. struct A, struct B, struct C
  3. When the application starts, I want to call start() on structs A, B and C
  4. Similarly, when the application terminates, I want to call stop() on the A, B, C structs.
  5. I do not want to hard code struct A, B and C anywhere in the code to call the start/stop functions. This is so that when I add struct D later (also implements interface I), the code will automatically work without modification.
  6. In order to achieve this, I need to be able to say "Hey Go, give me all the types that implement interface I".
  7. If I get back a slice of A, B and C, I can simply loop through and call the right methods at the right time.

Doable in Go?

like image 393
sat Avatar asked May 09 '14 05:05

sat


1 Answers

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.

like image 83
ANisus Avatar answered Nov 12 '22 13:11

ANisus