将 Option<impl Trait> 转换为 Option<Box<dyn Trait>>

zma*_*man 7 rust

是否可以将 an 映射Option<impl Trait>到 a Option<Box<dyn Trait>>?如果 的参数new()不是 an Option,则可以将其分配给structwith Some(Box::new(item))。为什么这个可以用而地图却不行?

trait TestTrait {}

impl TestTrait for i32 {}

struct TestStruct {
    item: Option<Box<dyn TestTrait>>
}

impl TestStruct {
    pub fn new(item: Option<impl TestTrait + 'static>) -> Self {
        let item: Option<Box<dyn TestTrait>> = item.map(|i| Box::new(i));
        Self {
            item
        }
    }
}


fn main() {    
    let num:i32 = 0;
    let s = TestStruct::new(Some(num));
}
Run Code Online (Sandbox Code Playgroud)

Max*_*axV 6

编译器似乎无法推断闭包的正确类型。如果您明确指定它,则一切正常(playground):

trait TestTrait {}

impl TestTrait for i32 {}

struct TestStruct {
    item: Option<Box<dyn TestTrait>>
}

impl TestStruct {
    pub fn new(item: Option<impl TestTrait + 'static>) -> Self {
        let item = item.map(
            |i| -> Box<dyn TestTrait> {
                Box::new(i)
            }
        );
        Self {
            item
        }
    }
}

fn main() {    
    let num:i32 = 0;
    let _ = TestStruct::new(Some(num));
}
Run Code Online (Sandbox Code Playgroud)

  • `Box::new(i) as Box&lt;dyn TestTrait&gt;` 也足以防止编译器过度进行类型推断。 (3认同)