Why Box<dyn Trait> can be assigned a value?

hi, everyone
I can't figure out why let b: Box<dyn Trait> = Box::new(RealType) works, there seems to be two different types on left and right side.
Does the compiler make the magic??

        use std::marker::PhantomData;
        trait Foo {
            fn foo(&self);
        }
        struct Impl;
        impl Foo for Impl {
            fn foo(&self) {
                println!("Impl::foo");
            }
        }

        // why Box works here ???
        let _b: Box<dyn Foo> = Box::new(Impl);
        _b.foo();

        // 2--
        struct Container<T: ?Sized> {
            _maker: PhantomData<T>
        }
        impl<T: ?Sized> Container<T> {
            fn new() -> Self {
                Container {
                    _maker: PhantomData,
                }
            }
        }
        // error: doesn't compile, expected trait object `dyn Foo`, found struct `Impl`
        let r = Container::<Impl>::new();
        let rrr: Container<dyn Foo> = r;

This is an example of a type coercion, specifically an unsized coercion.

Thanks for the reference,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.