简体   繁体   中英

Converting an Option<impl Trait> to an Option<Box<dyn Trait>>

Is it possible to map an Option<impl Trait> to a Option<Box<dyn Trait>> ? If the argument to new() is not an Option , it is possible to assign it to a struct with Some(Box::new(item)) . Why does this work and the map doesn't?

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

It looks like the compiler can not inference the correct type for the closure. If you specify it explicitly then everything works ( 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM