Extensible registry of types

末鹿安然 提交于 2019-12-13 02:56:18

问题


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?


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!