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

7

是否可以将Option<impl Trait>映射到Option<Box<dyn Trait>>? 如果new()的参数不是Option,则可以将其分配给具有Some(Box::new(item))struct。 为什么这样可以工作而映射不能呢?

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));
}
1个回答

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));
}

3
Box::new(i) as Box<dyn TestTrait> 这样写也足以防止编译器过度推断类型。 - user2722968
嗨,@user2722968。是的,你完全正确。我也尝试使用Box::new::<turbofish>来移除闭包,但没有成功。 - MaxV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接