Rust Fundamentals · 15 XP Pro
The ? operator
Calling several fallible functions with match gets noisy. The ? operator
shortens it: placed after a Result, it gives you the Ok value, or returns the
Err from the current function right away.
use std::num::ParseIntError;
fn double_text(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.trim().parse()?; // early return on error
Ok(n * 2)
}
? only works in a function whose return type is a compatible Result. Here
"abc".parse::<i32>() fails with a ParseIntError, and that same error type is
what double_text returns.
Your task
Everything must be pub, because the tests use your crate as lesson. Use ?
rather than match.
pub fn add_texts(a: &str, b: &str) -> Result<i32, std::num::ParseIntError>parses both strings asi32and returns their sum.pub fn sum_all(items: &[&str]) -> Result<i32, std::num::ParseIntError>parses every item and returns the total. It stops at the first bad item and returns that error. An empty slice givesOk(0).