E0277 rust type_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
85%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.70 active
1.75 active
1.80 active

Root Cause

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

generic

中文

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

Official Documentation

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

Workarounds

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

中文步骤

  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

Dead Ends

Common approaches that don't work:

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

    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% fail

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