How can the caller distinguish an empty title from a busy runner? In examples/src/bin/ep07.rs, SubmitError::EmptyTitle identifies invalid input. SubmitError::Busy identifies unavailable capacity. submit() returns those outcomes through Result<String, SubmitError>.
A Laravel response may need different handling for validation failure and temporary unavailability. The Rust example preserves that distinction in enum variants. Ok carries the accepted title. Err carries the reason submission was rejected.
Predict the result of each input before running: a blank title with an idle runner, a valid title with a busy runner, and a padded title with an idle runner. Then check which branch of the final match produces the terminal message.
This lesson covers Result<T, E>, an error enum, and the ? operator. We'll validate a title, check whether the runner is busy, and let the caller decide what to print. It leaves out error-handling crates and error conversion. It assumes Tutorial 6.
Take a look at Example 1.
Example 1. Complete example (examples/src/bin/ep07.rs)
#[derive(Debug, PartialEq)]
enum SubmitError { EmptyTitle, Busy }
fn normalize(title: &str) -> Result<String, SubmitError> {
let title = title.trim();
if title.is_empty() {
return Err(SubmitError::EmptyTitle);
}
Ok(title.to_owned())
}
fn submit(title: &str, busy: bool) -> Result<String, SubmitError> {
let title = normalize(title)?;
if busy { return Err(SubmitError::Busy); }
Ok(title)
}
fn main() {
assert_eq!(submit(" ", false), Err(SubmitError::EmptyTitle));
assert_eq!(submit("Run tests", true), Err(SubmitError::Busy));
assert_eq!(submit(" Run tests ", false), Ok("Run tests".into()));
match submit("Run tests", true) {
Ok(title) => println!("accepted: {title}"),
Err(SubmitError::EmptyTitle) => println!("enter a title"),
Err(SubmitError::Busy) => println!("runner busy; nothing started"),
}
}
Run it from the examples/ directory. Your three predictions are the three assertions in main: the blank title gives EmptyTitle, the valid title with a busy runner gives Busy, and the padded title gives the normalized success value Run tests.
Expected output:
cargo run --quiet --bin ep07
runner busy; nothing startedThe title that was not the problem
submit checked the title before it checked anything else. On the last call in main the title was "Run tests", nine characters with nothing at either end for trim to remove, and normalize handed it back inside Ok as an owned String. submit took the string out with ? and considered the title settled. Its next line asked whether the runner was busy. The second argument was true. submit returned Err(SubmitError::Busy), and the third arm of the match printed runner busy; nothing started.
Sometimes an operation can fail in more than one way and the callers need to respond differently to each. Thankfully, the return type can keep the failures apart. Take another look at Example 1.
There are three pieces. SubmitError is an enum with a variant per failure the caller can act on. normalize and submit return Result<String, SubmitError>: Ok with the value or Err with the error. And the match in main is where text finally appears, choosing the display for each variant, one arm per outcome. normalize trims the input before checking emptiness, and submit then checks busy.
What does the question mark do?
normalize(title)? extracts the string from Ok. If normalize returns Err(SubmitError::EmptyTitle), the ? returns that failure from submit immediately, and the busy check is not reached in that branch. Both functions use the same error type, so this example needs no error conversion.
Notice the order. A fourth case, a blank title with busy = true, would still return EmptyTitle, because normalization runs first. That precedence is a policy, and it lives in submit's control flow.
Keep the structure until the display boundary
An enum is useful when callers act differently per variant. The UI can invite a correction for EmptyTitle and show a waiting state for Busy. A terminal can map them to messages and exit codes. An HTTP adapter can choose status codes without parsing English prose. Convert every error to a String early and a copy edit can change behavior, because some caller is looking for the word “busy”.
You can also go broader. A library that promises structured recovery needs a stable contract; an application boundary may reasonably collect diagnostic context in a wider error type. If you're unsure, I'd match the amount of structure to what callers can use.
Where panics fit
Calling unwrap on an Err panics. That can be appropriate in a tightly controlled example, or for a condition the program treats as an invariant. A panic is not Rust's version of every PHP exception: PHP code uses exceptions for many recoverable conditions, and Rust commonly represents those with Result. A busy runner is ordinary here, so it belongs in the return contract.¹
Failure does not undo history
Imagine the real submit writes to a database, sends a message, and then loses the response. Returning Err tells the caller something failed, and it does not, whatever the word “error” suggests and however reasonable it would be to hope so, tell the caller that nothing happened, so a retry issued on the strength of that Err can run the write a second time unless the operation's contract was built for it.
The demonstration prints “nothing started” because it performs no external work before the Busy return. Error wording is a behavioral claim; add side effects and that message has to be justified again. Your Laravel knowledge transfers directly: transactions, idempotency keys, after-commit dispatch, and explicit retry policies are application responsibilities. Result carries the outcome.
So the three assertions pass and each failure has a name. Now imagine a caller that retries every Err. Which of your own errors would a retry repair, and which would it repeat? Does the calling code know the difference, or does it catch them all in one place?
Testing
In Example 1, add SubmitError::TitleTooLong. Define a length limit in normalize, then add the corresponding arm to the match in main. Before you write the failure assertion, predict whether a rejected title should be retried unchanged.
A length rejection requires corrected input; waiting alone does not repair the title. State what the limit counts: UTF-8 bytes, Unicode scalar values, or user-perceived characters. String::len() counts bytes, while .chars().count() counts scalar values. Assert the returned variant. If submission later writes tasks, also assert that invalid input leaves the task count unchanged.
Last, reconstruct submit as three steps: normalize the title, reject a busy runner, then return the accepted string.
TL;DR
Result<T, E> is Ok(value) or Err(error). An error enum keeps the distinctions callers act on, and its variants preserve the step that failed. ? returns early with a failure, so the order of the checks in submit is a policy. Text belongs at the display boundary: the terminal wording lives in main and can change without replacing the structured outcomes. Panics are for invariants and controlled examples. Err reports an outcome and undoes nothing. Next: making the behavior behind an operation replaceable with a trait.
¹ Panic recovery is not a general substitute for designing application errors, and a panic does not automatically roll back remote effects. An assertion inside a test is different: if the observed result violates the test's expectation, failing the test is what we want.