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 (Ok, Err)
- 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
'Personal-Study > Rust' 카테고리의 다른 글
[Rust 문서 읽기] 4. Understanding Ownership (소유권 이해하기) (0) | 2023.01.29 |
---|---|
[Rust 문서 읽기] 3. Common Programming Concepts (보편적인 프로그래밍 개념) (0) | 2023.01.29 |
[Rust 문서 읽기] 1. Getting Started (시작하기) (0) | 2023.01.28 |
[Rust 문서 읽기] Introduction (소개) (0) | 2023.01.28 |
[Rust 문서 읽기] Foreword (들어가기에 앞서) (0) | 2023.01.28 |
댓글