You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Inferring the resulting type of Box::downcast_unsafe complains about dyn Any not being sized. However if the type is specified directly, everything works as expected.
I tried this code:
pubstructBoxWrapper<T:Any>{data:Box<dynAny>,_phantom:PhantomData<T>,}impl<T:Any>BoxWrapper<T>{pubfndowncast<TTarget:Any>(self) -> Result<BoxWrapper<TTarget>,Self>{if !self.data.is::<TTarget>(){returnErr(self);}// let data: Box<TTarget> works finelet data:Box<_> = unsafe{self.data.downcast_unchecked()};Ok(BoxWrapper{
data,_phantom:PhantomData,})}}
This creates the following error message:
error[E0277]: the size for values of type `dyn Any` cannot be known at compilation time
--> src/lib.rs:22:47
|
22 | let data: Box<_> = unsafe { self.data.downcast_unchecked() };
| ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Any`
note: required by an implicit `Sized` bound in `Box::<(dyn Any + 'static), A>::downcast_unchecked`
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1820:38
|
1820 | pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
| ^ required by the implicit `Sized` requirement on this type parameter in `Box::<dyn Any, A>::downcast_unchecked`
However specifying the type directly (let data: Box<TTarget> = ... ) does not produce an error.
I would expect to either get no error message, or an error stating that the type can not be inferred.
The type you defined in your struct is Box<dyn Any>. This is the type that gets correctly inferred. It also correctly can't be downcast to because it's unsized. If you specify a concrete type to downcast to, what you are doing is downcasting and then unsizing again, which is really a no-op.
Inferring the resulting type of
Box::downcast_unsafe
complains aboutdyn Any
not being sized. However if the type is specified directly, everything works as expected.I tried this code:
This creates the following error message:
However specifying the type directly (
let data: Box<TTarget> = ...
) does not produce an error.I would expect to either get no error message, or an error stating that the type can not be inferred.
Meta
rustc --version --verbose
:The text was updated successfully, but these errors were encountered: