[SOLVED] Into<Option> for trait objects


I've got a problem making a function applies Into<Option<Box<dyn ToString>>>. The compiler says that trait From for the type but I don't understand why. It's possible to use Into<Option> with a concrete type and it's possible to use Option with a trait object. Could somebody explain it, please?


You are trying to go through too many hoops: from some concrete type T : ToString + 'static (such as T = &'static str for instance), you want to go to Box<T> then coerce to Box<dyn ToString + 'static> then wrap that in a Some() with the impl Into<Option< ... >> genericity.

That's far too much for Rust (mainly the Boxing thing, since a heap-allocation should be explicit).

So, by skipping the whole "Box for me", you can have a signature that does the rest (coercion and Some-wrapping):

fn call_trait_object<T : ToString + 'static> (
    val: impl Into<Option< Box<T> >>,
    let val: Option<Box<dyn ToString + 'static>> =
        val.into().map(|it| it as _)
    // ...

fn main ()

But then call_trait_object(None) fails because of type inference...

The other Option is to keep the signature you had, but help it when providing a parameter:

call_trait_object(Box::new("some text") as Box<dyn ToString>); // no error

Ok, I get the image. Thanks a lot! Solved.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.