Search code examples
rustconvention

Extensible registry of types


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 AudioFileReaders 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?


Solution

  • 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.