E0596 rust type_error ai_generated true

error[E0596]: cannot borrow data in a dereference of `*const T` as mutable

ID: rust/e0596-cannot-borrow-data-in-a-dereference-of-raw-pointer

Also available as: JSON · Markdown · 中文
85%Fix Rate
85%Confidence
1Evidence
2023-09-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
rustc 1.70.0 active
rustc 1.75.0 active
rustc 1.80.0 active

Root Cause

Attempting to mutate data through a raw const pointer (*const T), which is immutable by definition.

generic

中文

试图通过原始常量指针 (*const T) 修改数据,而该指针本质上是不可变的。

Official Documentation

https://doc.rust-lang.org/error_codes/E0596.html

Workarounds

  1. 95% success Change the pointer type to *mut T at the definition site. Example: let ptr: *mut T = &mut value as *mut T;
    Change the pointer type to *mut T at the definition site. Example: let ptr: *mut T = &mut value as *mut T;
  2. 80% success If you must keep *const T, use std::ptr::addr_of_mut! or cast to *mut T with a safety justification. Example: let mut_ptr = const_ptr as *mut T;
    If you must keep *const T, use std::ptr::addr_of_mut! or cast to *mut T with a safety justification. Example: let mut_ptr = const_ptr as *mut T;
  3. 90% success Refactor to use Cell or RefCell for interior mutability, avoiding raw pointers entirely. Example: let cell = Cell::new(42);
    Refactor to use Cell or RefCell for interior mutability, avoiding raw pointers entirely. Example: let cell = Cell::new(42);

中文步骤

  1. Change the pointer type to *mut T at the definition site. Example: let ptr: *mut T = &mut value as *mut T;
  2. If you must keep *const T, use std::ptr::addr_of_mut! or cast to *mut T with a safety justification. Example: let mut_ptr = const_ptr as *mut T;
  3. Refactor to use Cell or RefCell for interior mutability, avoiding raw pointers entirely. Example: let cell = Cell::new(42);

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The cast is allowed in unsafe code, but if the original memory is read-only (e.g., pointing to a static), mutation causes UB. The error is a safety warning.

  2. 90% fail

    The compiler correctly rejects this because *const T doesn't guarantee mutability. You need *mut T explicitly.

  3. 40% fail

    This changes the API contract; callers with *const T will no longer compile without a cast.