如何在 Rust 中将字符串转换为整数?

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

从 stdin 读取输入会产生 String,但如何将其转换为整数?

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);
}

使用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);
}

请注意,从字符串中解析数字可能会失败,因此 Result is returned. For this example, we panic on a failure case using expect

此外,read_line 离开按 Enter 的换行符,因此 trim 用于在解析之前忽略它。