Rust 기초

Reading User Input in Rust

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

  • 초급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

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

실행 가능한 Rust 예제

Rust
코드 실행 →
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."),
    }
}
이 예제의 실행 버튼 만들기 코드 실행 결과
What is your name?
How old are you?
Hello, Ada! Next year you will be 37.

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Conditions with if and else →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지