Learning question: What should a failed call return so that the caller can decide what to do next, and has what it needs to do it?
A send can fail for more than one reason, and the reasons call for different responses. This article reads the error type std returns from SyncSender::try_send: its two variants, and the field both of them carry.
Scope. We read library/std/src/sync/mpsc.rs at Rust 1.100.0 [S3]. We do not cover ?, error conversion with From, or error-handling crates. You need enums with data and match. The Rust patterns book places Result in the family of types that encode failure in a function's signature in place of exceptions [S2, ch. 12, "The Result and Option patterns"].
A match that expected one kind of bad news
Example 1 sends a report on a bounded channel and prepares for the channel to be full. The 1 passed to sync_channel is bound, the size of the channel's internal buffer [S3, lines 538 to 539].
Example 1. Does not compile (compile-fail/cf09_typed_results.rs, lines 4 to 8)
let (tx, _rx) = sync_channel::<String>(1);
match tx.try_send("report".to_string()) {
Ok(()) => println!("sent"),
Err(TrySendError::Full(msg)) => println!("busy, keeping {msg}"),
}
The match had two arms and took them to be the whole of the matter. One was for success. The other was for a full channel, and it had even thought to keep the message, which it laid by like a second umbrella. It had no arm for the day the receiver was gone. The compiler had the list of days.
error[E0004]: non-exhaustive patterns: `Err(TrySendError::Disconnected(_))` not covered
--> cf09_typed_results.rs:5:11
|
5 | match tx.try_send("report".to_string()) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pattern `Err(TrySendError::Disconnected(_))` not coveredPredict
try_send takes the String by value. Before reading on: when the send fails, where is the string? If the answer were "gone", what would retrying require?
Name the parts
| Part | In std | Where [S3] |
|---|---|---|
| The call | SyncSender::try_send(&self, t: T) |
mpsc.rs line 767 |
| The typed failure | enum TrySendError<T> |
line 470 |
| Its alternatives | Full(T), Disconnected(T) |
lines 478 and 483 |
What comes back?
Sometimes a call fails and all you get is a message, and the code that should react differently to "try again later" and "never try again" has to read prose to tell them apart. Thankfully, the failure can be a type. Take a look at Example 2.
Example 2. The error and the call (library/std/src/sync/mpsc.rs, lines 470 to 484 and 767, attributes and doc comments removed [S3])
pub enum TrySendError<T> {
Full(T),
Disconnected(T),
}
pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>>
There are two things to see. The enum has two variants, and they mean different things for the caller: Full says that, for a buffered channel like this one, the buffer is full at this time (lines 471 to 476); Disconnected says the channel's receiving half has disconnected (lines 480 to 481), and a sync_channel supports only one Receiver (lines 544 to 545), so there is no other receiver to wait for. And both variants hold a T. That is the answer to the prediction. The value you passed in was moved into try_send; on failure it is moved back out to you inside the error.
What transfers, and what does not
Catching two exception classes in PHP is the nearest habit, and the instinct to give each failure its own type transfers directly. Two things do not. The function declarations in the PHP manual show no list of exceptions [S4], and an exception that no catch block catches unwinds to the global scope and ends the program with a fatal error [S5], which is a report at run time; here the failures are in the return type, and Example 1 shows the check. And a PHP exception has no need to return your argument: PHP passes arguments by value by default [S4], and for an object that value is a copy of an identifier that points to the same object [S6], so the caller's variable is still usable after the call. In Rust the caller gave the value away, so an error that does not carry it back has destroyed it. You saw the same move in the Newtypes article, where FromUtf8Error returned the bytes.
What will the caller do with it?
So each failure has a name and the message survives. How many variants an error of your own should have is a question about its callers and not about the function that fails, because a variant belongs in the enum when some caller would branch on it, and an enum with eleven variants that every caller matches with a wildcard arm has told nobody anything, while a single Other(String) forces the one caller that needed to retry to compare text. For each failure your function can report: is there a caller that would do something different because of it?
Practice tier: compiler, for exhaustive matching. Choosing the variants is judgment.
Testing
The claim is that both failures are distinguishable and both return the value. Example 3 would fail if either variant dropped the message.
Example 3. Both refusals, both messages (tests/p09_typed_results_try_send.rs, abridged)
let (tx, _rx) = sync_channel::<String>(1);
tx.try_send("first".to_string()).unwrap();
match tx.try_send("second".to_string()) {
Err(TrySendError::Full(msg)) => assert_eq!(msg, "second"),
other => panic!("expected Full, got {other:?}"),
}
let (tx, rx) = sync_channel::<String>(1);
drop(rx);
match tx.try_send("orphan".to_string()) {
Err(TrySendError::Disconnected(msg)) => assert_eq!(msg, "orphan"),
other => panic!("expected Disconnected, got {other:?}"),
}
Both tests passed on rustc 1.100.0.
Retrieve
- Which variant means "trying again could work"?
- Why does each variant of
TrySendError<T>contain aT?
The Actors article uses a bounded channel as a mailbox; "full" there is how the owner says it is behind.
TL;DR
SyncSender::try_send returns Result<(), TrySendError<T>>. The error is an enum with two variants, Full and Disconnected, so the caller can tell a temporary refusal from a permanent one, and a match that forgets one does not compile. Both variants carry the unsent value, because the caller moved it into the call and would otherwise have lost it.