Skip to content

Casting owned type to raw pointer has unclear error message #84213

@nschoellhorn

Description

@nschoellhorn

Given the following code:

struct Something {
    pub field: u32,
}

fn main() {
    let something = Something {
        field: 1337,
    };
    
    let pointer_to_something = something as *const Something;
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1a1c55703dee4ed2078b5c704bd1f379

The current output is:

error[E0605]: non-primitive cast: `Something` as `*const Something`
  --> src/main.rs:10:41
   |
10 |     let pointer_to_something = something as *const Something;
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object

I think, that in the context of casting to a pointer, the output in this case should make it clear that the error could be fixed by taking a reference to the type and cast the reference to a raw pointer.
Example:

error[E0605]: non-primitive cast: `Something` as `*const Something`
  --> src/main.rs:10:41
   |
10 |     let pointer_to_something = something as *const Something;
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot cast an owned type to a raw pointer
   |     consider borrowing here: &something as *const Something

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler 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