본문 바로가기
Rust

[Rust] Guess 예제 (20일차)

by 꾸압 2023. 1. 1.

 

<예제 코드_1>

fn main() {
    let secret_number = 5;
    let mut guess = String::new();

    println!("Please enter your guess:");
    std::io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    let guess: u32 = match guess.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            println!("Please enter a number!");
            return;
        },
    };

    if guess == secret_number {
        println!("You guessed it!");
    } else {
        println!("Sorry, try again.");
    }
}

 


 

<예제 코드_2>

fn main() {
    let secret_number = 5;
    let mut guesses = Vec::new();

    loop {
        println!("Please enter your guess:");
        let mut guess = String::new();
        std::io::stdin().read_line(&mut guess)
            .expect("Failed to read line");

        let guess : u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Please enter a number!");
                continue;
            },
        };

        guesses.push(guess);
        
        if guess == secret_number {
            println!("You guessed it!");
            break;
        } else {
            println!("Sorry, try again.");
        }
    }

    println!("You took {} guesses.", guesses.len());
}

 


 

<참조 1> https://chat.openai.com/chat

 

 

'Rust' 카테고리의 다른 글

[Rust] Generic 예제 (22일차)  (0) 2023.01.04
[Rust] Enum 예제 (21일차)  (0) 2023.01.02
[Rust] Error 처리 Result 예제 (19일차)  (0) 2023.01.01
[Rust] String 예제 (17일차)  (0) 2022.12.28

댓글