E0596 rust type_error ai_generated true

错误[E0596]: 无法将 `*const T` 解引用中的数据借用为可变

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

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2023-09-20首次发现

版本兼容性

版本状态引入弃用备注
rustc 1.70.0 active
rustc 1.75.0 active
rustc 1.80.0 active

根因分析

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

English

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

generic

官方文档

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

解决方案

  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);

无效尝试

常见但无效的做法:

  1. 70% 失败

    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% 失败

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

  3. 40% 失败

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