Trait core::ops::CoerceUnsized
source · pub trait CoerceUnsized<T: ?Sized> { }
coerce_unsized
#18598)Expand description
Trait that indicates that this is a pointer or a wrapper for one, where unsizing can be performed on the pointee.
See the DST coercion RFC and the nomicon entry on coercion for more details.
For builtin pointer types, pointers to T
will coerce to pointers to U
if T: Unsize<U>
by converting from a thin pointer to a fat pointer.
For custom types, the coercion here works by coercing Foo<T>
to Foo<U>
provided an impl of CoerceUnsized<Foo<U>> for Foo<T>
exists.
Such an impl can only be written if Foo<T>
has only a single non-phantomdata
field involving T
. If the type of that field is Bar<T>
, an implementation
of CoerceUnsized<Bar<U>> for Bar<T>
must exist. The coercion will work by
coercing the Bar<T>
field into Bar<U>
and filling in the rest of the fields
from Foo<T>
to create a Foo<U>
. This will effectively drill down to a pointer
field and coerce that.
Generally, for smart pointers you will implement
CoerceUnsized<Ptr<U>> for Ptr<T> where T: Unsize<U>, U: ?Sized
, with an
optional ?Sized
bound on T
itself. For wrapper types that directly embed T
like Cell<T>
and RefCell<T>
, you
can directly implement CoerceUnsized<Wrap<U>> for Wrap<T> where T: CoerceUnsized<U>
.
This will let coercions of types like Cell<Box<T>>
work.
Unsize
is used to mark types which can be coerced to DSTs if behind
pointers. It is implemented automatically by the compiler.