How to typecast in rust

use std::io;
fn main() {
    let mut input = String::new();
    let mut T: i32 = 0;

    io::stdin().read_line(&mut input);
    T = input.parse().unwrap();

    println!("{}",T);
}

Why this code does not work ?, How to type cast.

The code compiles in the playground. Could you provide the error you receive and what input you're typing on stdin?

1 Like

In Python this works:

>>> int(" 10\n")
10

But in Rust and other language the string->int conversion works only if there's no whitespace around the number. I don't know why... So you need to call strip() before performing parse().

Also, read the warnings your compiler gives you and improve your code accordingly. And when you have a problem, give the compiler errors and details of your troubles.

Your code with small changes:

fn main() {
    use std::io::stdin;

    let mut input = String::new();
    let _ = stdin().read_line(&mut input);

    let t: i32 = input.trim().parse().unwrap();
    println!("{}", t);
}
5 Likes