E0277 rust type_error ai_generated true

错误[E0277]:`std::cell::Cell<i32>` 无法在线程间安全共享

error[E0277]: `std::cell::Cell<i32>` cannot be shared between threads safely

ID: rust/e0277-send-not-satisfied-for-arc-cell

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

版本兼容性

版本状态引入弃用备注
1.70 active
1.75 active
1.80 active

根因分析

在期望为 Send 的共享所有权容器(如 Arc)中使用了非 Send 类型(如 Cell)。

English

Using a non-Send type like Cell inside an Arc or other shared ownership container that is expected to be Send.

generic

官方文档

https://doc.rust-lang.org/error-index.html#E0277

解决方案

  1. Replace Cell with Mutex inside Arc: `Arc<Mutex<i32>>` instead of `Arc<Cell<i32>>`
  2. Use `RwLock` if read-heavy workload: `Arc<RwLock<i32>>`
  3. For single-threaded context, use `Rc<RefCell<i32>>` instead of Arc

无效尝试

常见但无效的做法:

  1. Wrapping Cell in Arc directly without any synchronization 95% 失败

    Arc<Cell<T>> is not Send because Cell is !Send. The compiler correctly rejects this.

  2. Using Mutex<Cell<T>> but forgetting to implement Send manually 70% 失败

    Mutex<Cell<T>> is Send if T: Send, but Cell is !Send, so it still fails. Need to switch to Mutex<T> directly.