Why does a Rust function returning Result<(), Box<dyn Error>> fail inside thread::spawn, and what does adding Send + Sync change?
answer
- trait objects forget auto traits
- spawn needs T: Send
- Arc sharing needs Sync
- io::Error::new's bound
basics
~20 sA dyn Error trait object promises only Error, not Send, so the Result cannot leave a spawned thread and rustc reports E0277. Box<dyn Error + Send + Sync> admits only thread-safe errors, which spawn, Arc sharing and io::Error::new all need.
solid answer
~50 s`thread::spawn` requires the closure's return type to be `Send + 'static`. `Box<dyn Error>` erases the concrete type and keeps only the traits written in the type, so rustc cannot prove the box is `Send` and reports E0277: `` `dyn std::error::Error` cannot be sent between threads safely ``. Writing `Box<dyn Error + Send + Sync>` moves the check to the conversion: only error types that are `Send` and `Sync` can be boxed into it, so an error holding an `Rc` is rejected where it is created, not where it is sent. `Sync` matters when the error is shared by reference across threads, as through an `Arc`, and `std::io::Error::new` takes `Into<Box<dyn Error + Send + Sync>>`, so a custom error must be both to travel inside an `io::Error`. The `Send + Sync` box coerces into a plain `Box<dyn Error>`, but not the other way.
code
rust · 11 linesuse std::error::Error;
use std::thread;
fn charge() -> Result<(), Box<dyn Error>> {
Err("gateway timeout".into())
}
fn main() {
let handle = thread::spawn(|| charge());
let _ = handle.join();
}go deeper
Recall that Box<dyn Error + Send + Sync> is the catch-all error type to use when errors may cross threads, and that plain Box<dyn Error> cannot leave a spawned thread.
Explain that trait objects carry only the auto traits written in their type, why spawn needs Send, and why Arc sharing additionally needs Sync.
Show you move the thread-safety check to where errors are created, keep Rc and RefCell out of error fields, and pin the guarantee with a compile-time assertion.
Set the catch-all type once for a codebase: defaulting to the Send + Sync form costs nothing at run time and avoids retrofitting bounds across every signature later.
## Trait objects forget auto traits `Box<dyn Error>` is a **trait object**: the box holds some concrete error, and the type records only the traits listed after `dyn`. **Auto traits** such as `Send` (safe to move to another thread) and `Sync` (safe to share by reference between threads) are implemented automatically for concrete types whose fields allow it, but a trait object has them only when the type says so. `Box<dyn Error>` therefore is **not** `Send`, even if every error you ever put in it happens to be — the compiler cannot see what is inside. ## The spawn failure `std::thread::spawn` is declared with `F: FnOnce() -> T`, `F: Send + 'static` and `T: Send + 'static`: whatever the thread returns is moved back to the thread that calls `join`. A closure returning `Result<(), Box<dyn Error>>` breaks that bound, and rustc 1.99.1 reports: - E0277: `` `dyn std::error::Error` cannot be sent between threads safely ``, - with notes walking outward: required for `Box<dyn Error>`, then for the `Result`, then by the bound in `spawn`. The fix is in the type, not in the thread code: return `Result<(), Box<dyn Error + Send + Sync>>`. ## Where the check moves With the bounds in the type, every conversion **into** the box demands them. std's generic `From<E>` impl for `Box<dyn Error + Send + Sync>` requires `E: Error + Send + Sync`, so the check happens where the error is created. An error type that stores an `Rc<String>` is rejected right there with E0277, `` `Rc<String>` cannot be sent between threads safely ``, pointing at the `.into()` or `?` that tried to box it. That is the useful place for the failure: next to the field that broke thread safety, not three modules away at a `spawn` call. Strings still work: std implements `From<String>` and `From<&str>` for `Box<dyn Error + Send + Sync>`, so `Err("gateway timeout".into())` compiles unchanged. ## What `Sync` adds `Send` alone covers moving the error out of a thread. `Sync` covers **sharing** it: `Arc<T>` is `Send` only when `T: Send + Sync`, so an error kept in an `Arc` and handed to several threads (a cached failure reported to every waiting request, say) needs both. The Rust API Guidelines make the same two points — an error that is not `Send` cannot be returned by a thread run with `thread::spawn`, and one that is not `Sync` cannot be passed across threads using an `Arc` — and add a third: `std::io::Error::new` requires `Error + Send + Sync`, so a custom error must be both to be packaged into an `io::Error`. ## Converting between the flavours | From | To | Result | |---|---|---| | `E: Error` | `Box<dyn Error>` | `From` impl; works for any error | | `E: Error + Send + Sync` | `Box<dyn Error + Send + Sync>` | `From` impl; rejects non-thread-safe errors | | `Box<dyn Error + Send + Sync>` | `Box<dyn Error>` | implicit coercion; the markers are dropped | | `Box<dyn Error>` | `Box<dyn Error + Send + Sync>` | rejected with E0308, mismatched types | Dropping a marker is always sound, so the coercion is free. Adding one would require a proof about a type the box has already erased, so rustc refuses. The bounds cost nothing at run time: both boxes are the same two-word pointer, data plus vtable, and the markers only change what compiles. ## Recognising the symptoms - **E0277 at a `spawn` call** naming `dyn std::error::Error` — the catch-all type lacks `+ Send`. - **E0277 at `.into()` or `?`** naming a field type such as `Rc<String>` — the target is `Send + Sync`, and the concrete error is not. - **E0308 at an assignment** between two boxed error types — code is trying to add markers back to a plain `Box<dyn Error>`. - A multi-threaded async runtime such as Tokio puts the same `Send` bound on a spawned task's output, so the same fix applies to a boxed error returned from a spawned task. ## Practical guidance 1. Make library error types `Send + Sync` by keeping thread-unsafe types such as `Rc`, `RefCell` and raw pointers out of their fields. 2. Lock that in with a compile-time check, as std does for `io::Error` internally: `fn _assert() { fn is<T: Send + Sync>() {} is::<PaymentError>(); }`. 3. Use `Box<dyn Error + Send + Sync>` rather than `Box<dyn Error>` as a catch-all in code that may ever run on more than one thread; the plain form suits code whose errors never cross a thread boundary. 4. Keep the implicit `'static` default of a boxed trait object: it lets the box cross `spawn` and lets callers downcast its contents.
- How can a payment library guarantee at compile time that `PaymentError` stays `Send + Sync`?Add a function that only compiles if the bounds hold: `fn _assert_send_sync() { fn is<T: Send + Sync>() {} is::<PaymentError>(); }`. If someone later adds an `Rc` field, the crate stops compiling with E0277 at that line. std uses the same trick for `io::Error` internally.
- Why does `Box<dyn Error + Send + Sync>` convert to `Box<dyn Error>` but not back?Coercing a trait object may drop auto traits, because forgetting a guarantee is always sound. Adding `Send` or `Sync` back would need proof about a concrete type the box has already erased, so rustc rejects the assignment with E0308, mismatched types. Pick the `Send + Sync` form at the source.
- Box<dyn Error> is Send whenever the error inside happens to be Send.
- Send alone is enough; Sync never matters for error values.
- Adding + Send + Sync makes the boxed error larger or slower.
- A Box<dyn Error> can be turned back into Box<dyn Error + Send + Sync> with into().
- The spawn failure is fixed by adding move to the closure.