我有一个函数,它搜索特征对象的列表,并试图找到一个实现者是特定类型的对象,但是编译器不接受返回类型。
pub struct GameObject{
pub modules: Vec<Box<dyn ModuleTrait>>,
}
impl GameObject {
pub fn find_module_of_type<T: ModuleTrait>(&self) -> Result<T> {
//iterate through the modules
self.modules
.iter()
.for_each(|m| {
let module = m.as_any().downcast_ref::<T>();
//see if mosule is of the correct type
if match module {
Some(T) => true,
None => false,
} {
return Ok(module); //this is where the error happens
}
});
Err(anyhow!("The specified module could not be found"))
}
}
pub trait ModuleTrait {
fn as_any(&self) -> &dyn Any;
}
pub struct Transform{
pub value: i32
}
impl ModuleTrait for Transform {
fn as_any(&self) -> &dyn Any {
self
}
}
这给出了错误
error[E0308]: mismatched types
--> src\scene\game_object.rs:42:28
|
42 | return Ok(module);
| ^^^^^^^^^^ expected `()`, found `Result<Option<&T>, _>`
|
= note: expected unit type `()`
found enum `std::result::Result<Option<&T>, _>`
note: return type inferred to be `()` here
--> src\scene\game_object.rs:42:28
|
42 | return Ok(module);
| ^^^^^^^^^^
For more information about this error, try `rustc --explain E0308`
错误消息让我更加困惑,因为它首先告诉我单元返回类型是推断的,但同时它不是单元类型。
我试图打开模块,但给出的错误信息大致相同