Rust cơ bản

Reading User Input in Rust

Read a line with read_line, trim it and parse it into a number without crashing on bad input.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • io::stdin().read_line
  • trim and parse
  • Handling bad input with match
From the keyboard to a number
  1. 1read_line"36\n"
  2. 2trim()"36"
  3. 3parse::<u32>()Ok(36)
  4. 4age + 137

Text in, number out

read_line waits for the user to type a line and press Enter, then adds the text to a String. The text always arrives as a string, so numbers must be parsed before you calculate with them.

trim removes the newline that read_line keeps at the end. parse::<u32>() returns Ok with the number or Err when the text is not a number, and match handles both cases. The sample output uses the answers Ada and 36: in the online compiler, type your answers when the prompts appear.

Những điểm quan trọng

  1. read_line keeps the newline: call trim.
  2. parse returns Ok(number) or Err.
  3. match handles both cases.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
use std::io;

fn main() {
    println!("What is your name?");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("failed to read");
    let name = name.trim();

    println!("How old are you?");
    let mut age = String::new();
    io::stdin().read_line(&mut age).expect("failed to read");

    match age.trim().parse::<u32>() {
        Ok(age) => println!("Hello, {name}! Next year you will be {}.", age + 1),
        Err(_) => println!("Hello, {name}! That is not a number."),
    }
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
What is your name?
How old are you?
Hello, Ada! Next year you will be 37.

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách