Skip to content

Unhelpful compiler suggestion when trying to dereference a pointer that is not Copy #126863

Closed

Description

Code

fn main() {
    let val = String::from("test");
    let p = std::ptr::addr_of!(val);
    unsafe {
        let inner: String = *p;
        dbg!(inner);
        std::mem::forget(val);
    }
}

Current output

error[E0507]: cannot move out of `*p` which is behind a raw pointer
 --> src/main.rs:5:29
  |
5 |         let inner: String = *p;
  |                             ^^ move occurs because `*p` has type `String`, which does not implement the `Copy` trait
  |
help: consider removing the dereference here
  |
5 -         let inner: String = *p;
5 +         let inner: String = p;
  |
help: consider cloning the value if the performance cost is acceptable
  |
5 -         let inner: String = *p;
5 +         let inner: String = p.clone();
  |

For more information about this error, try `rustc --explain E0507`.

Desired output

error[E0507]: cannot move out of `*p` which is behind a raw pointer
 --> src/main.rs:5:29
  |
5 |         let inner: String = *p;
  |                             ^^ move occurs because `*p` has type `String`, which does not implement the `Copy` trait
  |
help: consider using `ptr::read` to get the value the pointer refers to
  |
5 -         let inner: String = *p;
5 +         let inner: String = p.read();  
  |

For more information about this error, try `rustc --explain E0507`.

Rationale and extra context

Cloning the pointer doesn't make sense in that situation and would cause a type mismatch error. I'm not sure whether any of the two current suggestions should be kept or removed in this case.

Other cases

No response

Rust Version

rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: x86_64-unknown-linux-gnu
release: 1.79.0
LLVM version: 18.1.7

Anything else?

No response

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

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsD-papercutDiagnostics: An error or lint that needs small tweaks.Diagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant 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