The above should be called constructor. To be more clear:
let x: D<Box<dyn Trait>> = D<Box<dyn Trait>>{
a: Box::new(A{}) // the coercion is happening here
};
or more clear
fn constructor(a: Box<dyn Trait>) -> D<Box<dyn Trait>> {
D { a }
}
// coerce from Box<A> to Box<dyn Trait>
// &A -> &dyn Trait
let x: D<Box<dyn Trait>> = constructor(Box::new(A{});
You are mixing constructor with copy assign constructor, which Rust doesn't have. It's a good thing for Rust because a lot of implicit conversions can bring surprises when using operator=
in C++. In rust, you need to explicitly define logic to convert. More readable, IMO, rust emphasizes on explicity way more over implicity, for example, you can't index vector with u8
but you have to convert as usize
.
Box
is using Deref
, to convert from Box<B>
to Box<A>
(you can always imagine replacing Box with &, as &B
to &A
, coercion).
But you cannot assign struct type D<B>
to D<A>
, even though B can be coerced to A. The reason is that there's no copy assign logic for different struct type. (I doubt there's no =
operator overload for Rust, but I'm not sure).
struct D<T> {
template<class Other>
D& operator=(D<Other>& other) {
a = other.a;
return *this;
}
};
You need to define the From
logic on your own.
All in all. struct D<A>
= D<B>
is different with Box<A>
= Box<B>
, even though they look similar, the latter is using Defer
the former is using copy assign
or operator=
, which doesn't exist.
IMO, Rust needs to bring the concept constructor
and copy assign
into their official doc.
Besides that, the title of your post is too big...will affect other people's search if they post similar topic.