是否可以在 Rust 中创建泛型参数类型的实例?
我来自 C++ 背景,使用模板类型在实际函数体中创建类型是完全有效的。
我正在尝试T在此函数中创建一个具有类型的变量,但我不确定如何。
我只想能够创建一个 type 的对象T,加载它,然后将它插入到HashMap:
fn load<T>(&mut self, id: String, path: String)
where T: AssetTrait + 'static
{
// let asset : T = T; this doesn't work?
asset.load(path);
// self.assets.insert(id, Box::new<T>(asset));
}
Run Code Online (Sandbox Code Playgroud)
这是我的所有代码:
trait AssetTrait {
fn load(&self, path: String) {
// Do nothing
// Implement this in child asset object
}
}
struct AssetManager {
assets: HashMap<String, Box<AssetTrait + 'static>>,
}
impl AssetManager {
fn new() -> …Run Code Online (Sandbox Code Playgroud)