zman
zman

Reputation: 223

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

Upvotes: 8

Views: 2069

Answers (1)

MaxV
MaxV

Reputation: 2810

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

Upvotes: 7

Related Questions