본문 바로가기
Personal-Study/Rust

[Rust 문서 읽기] 2. Programming a Guessing Game (추리 게임 튜토리얼)

by Aaron-Kim 2023. 1. 29.

The Rust Programming Language

- 1~100 random number generated

   and then user guess the number, after that computer checks if correct or not and gives high/low hint

- Processing a Guess

 

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

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

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {guess}");

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}

 

  - Storing Values with Variables

    - :: means that new is an associated function of String type

  - Receiving User Input

    - & indicates that this argument is reference

  - Handling Potential Failure with Result

    Result is an enumeration (enum) -> purpose: encode error-handling information (OkErr)

    - If instance of Result is an Err value, expect will cause the program to crash and display the messages

  - Printing Values with println! Placeholders

  - Testing the First Part

- Generating a Secret Number

  - Using a Crate to Get More Functionality

  - Generating a Random Number

    - rand::Rng trait

- Comparing the Guess to the Secret Number

- Allowing Multiple Guesses with Looping

  - Quitting After a Correct Guess

  - Handling Invalid Input

- Summary


Programming a Guessing Game (영어)

추리 게임 튜토리얼 (한국어)

반응형

댓글