Home >Backend Development >Golang >How to Dynamically Discover Instances Implementing a Go Interface at Runtime?
Golang: Discovering Instances Implementing an Interface
In Golang, it is often desirable to perform operations on instances of a specific type or those implementing a particular interface. However, the language's strict typing presents a challenge in identifying all instances that satisfy a given criterion at runtime.
Problem Overview
Consider the following use case:
Solution Discussion
Golang's type system does not allow for the runtime retrieval of all types implementing an interface. This is because Go is statically typed, and the compiler eliminates unused types and methods to optimize the resulting binary.
Alternative Approach
An alternative solution is to maintain a global map or slice that associates an identifier with instances implementing the interface. Each struct can initialize itself by adding an instance to this global collection.
For example:
<code class="go">var instMap = map[string]StartStopper type A struct {} func init() { instMap["A"] = new(A) }</code>
During startup and termination, the program can iterate over the global collection and invoke the appropriate methods on each instance.
Extension for Multiple Instances
If multiple instances of each type can exist, the global collection must be updated whenever a new instance is created and removed when it is no longer in use. This ensures proper handling by the garbage collector.
The above is the detailed content of How to Dynamically Discover Instances Implementing a Go Interface at Runtime?. For more information, please follow other related articles on the PHP Chinese website!