-2

I'm learning Rust and am trying to add ints and I got this error:

        let c = a + b;
  |                 ^
  |                 |
  |                 expected `&str`, found struct `String`
  |                 help: consider borrowing here: `&b`

Here is my code:

use std::io;
fn main() {
    let mut a;
    let mut b;
    io::stdin().read_line(&mut a);
    io::stdin().read_line(&mut b);
    let c = a + b;
    println!("{c}");
}

I think it might be trying to concatenate a and b though I don't know.

I'm trying to add ints and get input from the user in Rust. Though I don't really know how to fix the error.

Jmb
  • 18,893
  • 2
  • 28
  • 55
Wallace
  • 1
  • 2

1 Answers1

0

From the signature of read_line:

pub fn read_line(&self, buf: &mut String) -> Result<usize>;

You can see that the buffer you pass it will be inferred to be a String. Before you can add your 2 inputs as numbers you have to convert them to numbers first:

let a = a.parse::<i32>().unwrap();
let b = b.parse::<i32>().unwrap();

you'll then run into the issue that you don't have your variables initialized which is an error in Rust so the whole fixed code would look something like this:

use std::io;
fn main() {
    let mut a = String::new();
    let mut b = String::new();
    io::stdin().read_line(&mut a);
    io::stdin().read_line(&mut b);
    let a = a.parse::<i32>().unwrap();
    let b = b.parse::<i32>().unwrap();
    let c = a + b;
    println!("{c}");
}
cafce25
  • 15,907
  • 4
  • 25
  • 31