Skip to content

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

Open
@theemathas

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 fd8d6fb).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-raw-pointersArea: raw pointers, MaybeUninit, NonNullA-trait-objectsArea: trait objects, vtable layoutC-discussionCategory: Discussion or questions that doesn't represent real issues.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions