Box::new
only works with sized types; that is, it takes a value of a sized type T
and returns Box<T>
. In certain places a Box<T>
can be coerced into a Box<U>
(if T: Unsize<U>
).
Such coercion does not happen in .map(Box::new)
, but does in Some(Box::new(s))
; the latter is basically the same as Some(Box::new(s) as Box<FooTrait>)
.
You could create (in nightly) your own box constructor that returns boxes of unsized types like this:
#![feature(unsize)]
fn box_new_unsized<T, U>(v: T) -> Box<U>
where
T: ::std::marker::Unsize<U>,
U: ?Sized,
{
Box::<T>::new(v)
}
and use it like .map(box_new_unsized)
. See Playground.