I have a struct MyStruct
that implements the trait MyTrait
.
How I can map Result<Box<MyStruct>>
to get Result<Box<dyn MyTrait>>
without passing to map()
an explicit lambda with the return type?
The code
#[derive(Debug)]
struct MyStruct;
trait MyTrait {}
impl MyTrait for MyStruct {}
#[derive(Debug)]
struct MyError;
type Result<T> = std::result::Result<T, MyError>;
fn foo(_: &mut dyn MyTrait) {}
fn main() {
let res: Result<MyStruct> = Ok(MyStruct {});
let res: Result<Box<dyn MyTrait>> = res.map(Box::new);
// let res: Result<Box<dyn MyTrait>> = res.map(|x| -> Box<dyn MyTrait> {
// Box::new(x) //too verbose
// });
foo(res.unwrap().as_mut());
}
causes the compile error
error[E0308]: mismatched types
--> src/main.rs:17:41
|
17 | let res: Result<Box<dyn MyTrait>> = res.map(Box::new);
| ^^^^^^^^^^^^^^^^^ expected trait MyTrait, found struct `MyStruct`
|
= note: expected type `std::result::Result<std::boxed::Box<dyn MyTrait>, _>`
found type `std::result::Result<std::boxed::Box<MyStruct>, _>`