From String to integer

As i said i'm noob.... another simple question:

use std::io;
use std::io::prelude::*;
fn main()
{
    print!( "Insert a number: ");
    io::stdout().flush().ok().expect("");
    let mut input01 = String::new();
    io::stdin().read_line(&mut input01);
    print!( "Insert another number: ");
    io::stdout().flush().ok().expect("");
    let mut input02 = String::new();
    io::stdin().read_line(&mut input02);
    let x01 = input01.parse::<i32>();
    let x02 = input02.parse::<i32>();
    let r01 = x01 + x02;
}

i get:
error: binary operation + cannot be applied to type core::result::Result<i32, core::num::ParseIntError> [E0369]
Am i using a wrong way to go from String to integer?

Thx.

parse may fail to parse the string, so it returns Result<T, E>, where E depends on what T is. In this case it's Result<i32, ParseIntError>. There's no implementation of the Add trait for Result<i32, ParseIntError>, so you can't add them together without handling or ignoring the errors.

1 Like

Ok, thx, i solved this way... if someone knows something better he is welcome

use std::io; use std::io::prelude::*; fn main() { print!( "Insert a number: "); io::stdout().flush().ok().expect(""); let mut input01 = String::new(); io::stdin().read_line(&mut input01); print!( "Insert another number: "); io::stdout().flush().ok().expect(""); let mut input02 = String::new(); io::stdin().read_line(&mut input02); let x01: i32 = input01.trim().parse() .ok() .expect("Please type a number!"); let x02: i32 = input02.trim().parse() .ok() .expect("Please type a number!"); let r01 = x01 + x02; println! ("{}", r01) }

1 Like

You don't need to write .ok().expect(...). Result does also implement expect in the latest version of Rust. I'm also not sure how good it is to use expect("") compared to unwrap()...

mmmhhhh ... it seems compiler complains if i remove .ok and .expect....

1 Like

Yes, you should use the result somehow. What I meant with not needing to write .ok().expect(...) is that just .expect(...) will do just fine, as in let x01: i32 = input01.trim().parse().expect("Please type a number!");.

1 Like

Ah ok :stuck_out_tongue_winking_eye:

This works for me, thanks :slight_smile: