类型的可扩展注册表 [英] Extensible registry of types
问题描述
我有一个可以读取多种音频格式的程序。共享模块可以提供一个特征, AudioFileReader
,该特征具有读取音频数据的通用方法以及用于将阅读器与文件扩展名相关联的注册表。
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.
而不是将所有可能的音频格式读取器内置到模块中,此模块的可扩展性将很有用,以便模块的客户端可以提供 AudioFileReader
用于新格式(通过链接到可执行文件或通过插件系统时)。
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).
用传统的Rust方式构建文件像这样的系统?有没有一种方法可以避免在不失去扩展性的情况下需要全局静态注册表?
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?
推荐答案
您可以使用 lazy_static
全局,其中包含扩展名到 Box< AudioFileReader>
的映射。
You can build such a registry by using a lazy_static
global, which contains a map of extension name to Box<AudioFileReader>
.
您必须将它们全部列在main中(或具有main调用init函数)。无法自动执行此操作,Rust在main之前没有生命。
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.
这篇关于类型的可扩展注册表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!