Can't cast a pointer of a trait object newtype to a pointer of that trait object. #128625
Open
Description
opened on Aug 4, 2024
I tried this code:
trait Trait {}
struct Wrap(dyn Trait);
fn cast(x: *mut Wrap) {
x as *mut dyn Trait;
}
I expected the code to compile. Instead, I got the following error, where it appears that the compiler is trying to do an unsize coercion and failing:
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `Wrap: Trait` is not satisfied
--> src/lib.rs:6:5
|
6 | x as *mut dyn Trait;
| ^ the trait `Trait` is not implemented for `Wrap`
|
help: this trait has no implementations, consider adding one
--> src/lib.rs:1:1
|
1 | trait Trait {}
| ^^^^^^^^^^^
= note: required for the cast from `*mut Wrap` to `*mut dyn Trait`
error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time
--> src/lib.rs:6:5
|
6 | x as *mut dyn Trait;
| ^ doesn't have a size known at compile-time
|
= help: within `Wrap`, the trait `Sized` is not implemented for `(dyn Trait + 'static)`, which is required by `Wrap: Sized`
note: required because it appears within the type `Wrap`
--> src/lib.rs:3:8
|
3 | struct Wrap(dyn Trait);
| ^^^^
= note: required for the cast from `*mut Wrap` to `*mut dyn Trait`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (lib) due to 2 previous errors
Of note, the following code compiles fine:
trait Trait {}
struct Wrap(dyn Trait);
fn cast(x: *mut Wrap) {
x as *mut (dyn Trait,);
}
Probably related to #128621
Meta
This issue reproduces on the playground on stable (1.80.0), and nightly (2024-08-02 fd8d6fb).
Activity