问题
I have a program that can read multiple audio formats. A shared module could provide a trait, AudioFileReader
, that has common methods for reading audio data as well as a registry for associating readers to file extensions.
Rather than have all the possible audio format readers built into the module, it would be useful for this module to be extensible, so that clients of the module can provide AudioFileReader
s for new formats (either when linked into an executable or via a plug-in system).
What would be a conventional Rust way to build a system like this? Is there a way to avoid needing a global static registry while without losing extensibility?
回答1:
You can build such a registry by using a lazy_static
global, which contains a map of extension name to Box<AudioFileReader>
.
You would have to list them all in main (or have main call init functions). There's no way to automatically do this, Rust has no life before main.
来源:https://stackoverflow.com/questions/44895392/extensible-registry-of-types