我试图理解为什么map
会触发编译错误,而match
表达式却不会。
我有:
use std::boxed::Box;
use std::io::Error;
trait MyTrait {
fn foo(&self);
}
struct MyStruct { }
impl MyTrait for MyStruct {
fn foo(&self) { }
}
我想编写一个函数,将MyStruct
的实例转换为Box<MyTrait>
的实例。
它将编译:
fn bar() -> Result<Box<MyTrait>, Error> {
let x = Ok(MyStruct {});
match x {
Ok(y) => Ok(Box::new(y)),
Err(err) => Err(err),
}
}
与此同时:
fn bar() -> Result<Box<MyTrait>, Error> {
let x = Ok(MyStruct {});
x.map(|y| Box::new(y))
}
给出错误:
error[E0308]: mismatched types
--> src\main.rs:16:2
|
14 | fn bar() -> Result<Box<MyTrait>, Error> {
| --------------------------- expected `std::result::Result<std::boxed::Box<MyTrait + 'static>, std::io::Error>` because of return type
15 | let x = Ok(MyStruct {});
16 | x.map(|y| Box::new(y))
| ^^^^^^^^^^^^^^^^^^^^^^ expected trait MyTrait, found struct `MyStruct`
|
= note: expected type `std::result::Result<std::boxed::Box<MyTrait + 'static>, std::io::Error>`
found type `std::result::Result<std::boxed::Box<MyStruct>, _>`
这两个bar()
实现之间有什么区别?