Rust The ? Operator
Propagate a typed failure without hiding which step failed.
How it works
The ? operator returns early from a compatible fallible context when it sees an error, otherwise extracting the success value. It reduces repetitive matching but does not choose recovery policy for the application. A helper can propagate an error while a boundary caller converts it into a message or status. Keep the error type informative enough for that decision.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
fn total(a: &str, b: &str) -> Result<u32, std::num::ParseIntError> { Ok(a.parse::<u32>()? + b.parse::<u32>()?) }
assert_eq!(total("3", "5"), Ok(8));
assert!(total("bad", "5").is_err());
println!("Two valid fields total 8; invalid field propagates an error");
}
Expected result
Two valid fields total 8; invalid field propagates an error
Each parse has the same error type, so ? can propagate it directly. The addition here uses small fixed inputs; a general count interface should use checked_add and an error type that also covers overflow. Propagation saves syntax, not the need to review all numerical and domain boundaries.
Primary technical reference: Rust documentation.