Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to make a program that adds a user's input and adds 2 to it, don't understand errors

use std::io; 

fn main() {
    let mut number_to_add = String::new();
    
    println!("what do you wanna add to two");

    io::stdin()
        .read_line(&mut number_to_add);

    let number_to_add: u32 = number_to_add.trim().parse();  {
        Ok(num) => num,
        Err() => continue,
    };

    let mut result = 2 + number_to_add;

    println!("result is {}", result);
}

Here is the error output:

error: expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`
  --> src/main.rs:12:17
   |
12 |         Ok(num) => num,
   |                 ^^ expected one of `.`, `;`, `?`, `}`, or an operator

error[E0308]: mismatched types
  --> src/main.rs:11:30
   |
11 |     let number_to_add: u32 = number_to_add.trim().parse();  {
   |                        ---   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `Result`
   |                        |
   |                        expected due to this
   |
   = note: expected type `u32`
              found enum `Result<_, _>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `mather` due to 2 previous errors

Before I get asked, yes, I have read the explanation with rustc and I do not understand it. I know that it’s probably expecting a number, but aren’t the .trim() and .parse() supposed to turn the user inputted string into a number?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to "open", or .unwrap() values in Rust which are wrapped or may result in a None.

use std::io; 

fn main() {
    let mut number_to_add = String::new();
    println!("what do you wanna add to two");

    io::stdin().read_line(&mut number_to_add);

    let number_to_add = number_to_add.trim().parse::<u32>().unwrap();

    let result = 2 + number_to_add;

    println!("result is {}", result);
}

Here’s a playground with a hardcoded value for the input.

Or, if you want to keep your Ok/Err block, it needs a match:

let number_to_add: i32 = match number_to_add.trim().parse::<u32>() {
    Ok(number) => number.try_into().unwrap(),
    Err(e) => panic!("{}", e),
};

let result = 2 + number_to_add;

println!("result is {}", result);

Updated playground here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading