Recover Unsent Values From SendError
When every receiver is dropped the send fails: SendError::into_inner hands back the owned value so the producer can retry or park the message.
Code
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
// 消费端全部退出后通道断开:继续 send 会得到 Err(SendError)
drop(rx);
let event = String::from("order:7 shipped");
match tx.send(event) {
Ok(()) => println!("delivered"),
Err(err) => {
// SendError 只包着被拒收的值:into_inner 完整取回所有权
let unsent = err.into_inner();
println!("receiver gone, kept for retry: {unsent}");
}
}
}The moment the channel breaks
mpsc::channel::<String>() pairs the producer tx with the receiver rx; drop(rx) closes the receiving end, so the very next tx.send(event) fails with Err(SendError). The match has two arms and this run takes the second: the delivered arm is dead code for this data, since no receiver exists to take the message.
What the producer recovers
receiver gone, kept for retry: order:7 shipped
SendError wraps exactly one thing — the value that was refused — and err.into_inner() hands back full ownership of it. The printed line proves the String came back intact, not cloned or truncated: the producer can retry it later or park it, which is the whole point of the recovery path.
The line that takes the value back
let unsent = err.into_inner();
println!("receiver gone, kept for retry: {unsent}");
Without into_inner the refused value would be unreachable inside the error; here the match arm turns a failed send into a retryable holding state with one call.
Interactive Tools for This Topic
FAQ
- What does Recover Unsent Values From SendError print when run?
- Invoke the file as-is — the `delivered`, `receiver gone, kept for retry:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.