Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a String to an integer in Rust? [duplicate]

Tags:

rust

Reading input from stdin produces a String, but how do I convert it to an integer?

use std::io;

fn main() {
    println!("Type something");

    let mut input = String::new();

    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    println!("{}", input);
}
like image 213
Gapry Avatar asked Dec 08 '22 04:12

Gapry


1 Answers

Use parse:

use std::io;

fn main() {
    println!("Type something");

    let mut line = String::new();

    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");

    let input: u32 = line
        .trim()
        .parse()
        .expect("Wanted a number");

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

Note that parsing a number from a string can fail, so a Result is returned. For this example, we panic on a failure case using expect.

Additionally, read_line leaves the newline from pressing Enter, so trim is used to ignore that before parsing.

like image 171
Shepmaster Avatar answered Jan 13 '23 01:01

Shepmaster