Can't cast a pointer of a trait object newtype to a pointer of that trait object.
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
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 fd8d6fbe505ecf913f5e).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the minimal reproduction in src/lib.rs and run it on stable and nightly, comparing the failing *mut dyn Trait cast with the compiling tuple form. Review related issue #128621, then establish the intended cast behavior and add a regression test; done means the expected cast compiles without the reported E0277 errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100