rust-lang / rust-lang/rust

Can't cast a pointer of a trait object newtype to a pointer of that trait object.

Open
#128,625 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-dyn-trait A-raw-pointers C-discussion T-types
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.