Does Rust intentionally prevent side effects calculating parameters?

The reason why you can't write chars.fold(chars.next()...) is the same as in this other recent thread, Why does this borrow last for whole statement? which contains several explanations. The use of chars is an expression that needs to be evaluated, and when the first one is evaluated, the value is moved out of the variable into temporary storage until the fold() call can happen, so it is not available for use again by .next().

Do you really need to treat the first digit differently from other digits? If not, then I would suggest a for loop (so that the error can be produced on any digit):

fn main() -> Result<(), Box<dyn std::error::Error>> {
    const RADIX: u32 = 10;
    let string = "2054";
    let mut a = 0;
    for c in string.chars() {
        a = a * 10 + c.to_digit(RADIX).ok_or("not a digit")?;
    }
    println!("{a}");
    Ok(())
}
3 Likes