Recursive "From" trait

Currently, the following code snippet doesn't compile, because From<{ integer }> isn't implemented for Box<Box<_>>.

type Container<T> = Box<Box<T>>;

fn main() {
    let container: Container<_> = 1000.into();
    println!("{}", container)
}

(Playground)

However, From<{ integer }> is implemented for Box<_> and From<Box<_>> is implemented for Box<Box<_>> - which means there is a route to get there.

Is there any reason why this isn't currently possible or won't be possible in Rust?

There is no implementation of From<{integer}> for Box<Box<{integer}>> so you can't do that automatically. Let's say I make the following implementations

impl From<i32> for Foo
impl From<Foo> for Box<Box<i32>>

How should Rust perforn the conversion? Via Box<i32> or via Foo. This ambiguity is why you can't do this.

It sounds like you're looking for a blanket implementation like:

impl<A: From<B>, B: From<C>> From<C> for A {
    fn from(v: C) -> A {
        A::from(B::from(v))
    }
}

However, if this implementation were to exist, this would prevent A from implementing From<C> directly for all cases where there's already B: From<C> and A: From<B>. That may not always be what you want.

Also note that there is an unconstrained generic parameter B, so this impl wouldn't compile anyways.

Thanks! I understand why this doesn't work a bit better.

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