E0277
rust
type_error
ai_generated
true
错误[E0277]:`Cell<i32>` 无法在线程间安全共享
error[E0277]: `Cell<i32>` cannot be shared between threads safely
ID: rust/e0277-send-not-implemented-for-arc-cell
85%修复率
88%置信度
1证据数
2023-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| rustc 1.68 | active | — | — | — |
| rustc 1.75 | active | — | — | — |
| rustc 1.82 | active | — | — | — |
| rustc 1.90 | active | — | — | — |
根因分析
尝试在线程间发送包含 `Cell`(它实现了 `!Send`)的类型,通常通过 `Arc<Cell<T>>` 或带有 `Cell` 字段的结构体。
English
Attempting to send a type containing Cell (which is !Send) across threads, typically via Arc<Cell<T>> or a struct with Cell field.
官方文档
https://doc.rust-lang.org/stable/error_codes/E0277.html解决方案
-
Replace Cell with Mutex: `let shared = Arc::new(Mutex::new(42));` then use `shared.lock().unwrap()` to access the value. This makes the type Send because Mutex<T> is Send if T: Send.
-
Use `std::cell::RefCell` with `Mutex` outer: `Arc<Mutex<RefCell<T>>>` if interior mutability is needed but the outer type must be Send.
-
If the value is only read, use `Arc<std::sync::RwLock<T>>` for better concurrency.
无效尝试
常见但无效的做法:
-
95% 失败
Arc<T> only implements Send if T: Send, and Cell is !Send, so Arc<Cell<i32>> remains !Send.
-
85% 失败
Unsafe impl of Send for a type containing Cell is unsound; the compiler will still reject it unless you also disable the lint, and it may cause data races at runtime.
-
90% 失败
The compiler correctly rejects because the closure captures a !Send type, even with move.