Back to questions
JuniorTheoryCommon
What does the program print?
use std::num::ParseIntError;
fn double(s: &str) -> Result<i32, ParseIntError> {
let n: i32 = s.parse()?;
Ok(n * 2)
}
fn main() {
println!("{:?} {}", double("21"), double("x").is_err());
}Ok(42) true
- Expecting
42 true:doublereturnsOk(n * 2), and{:?}prints aResultwith its variant, so the first value isOk(42). - Expecting
?to panic on the bad input likeunwrap: it returns theErrfromdouble, andis_err()turns it intotrue.
- What does
doublereturn for the inputx, printed with{:?}? - How would you write
doublewithout?, usingmatch?