当匹配表达式没有时,为什么Result :: map会出现编译错误?

时间:2018-08-05 15:34:24

标签: rust

我试图理解为什么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()实现之间有什么区别?

0 个答案:

没有答案