https://rust-book.cs.brown.edu/ch02-00-guessing-game-tutorial.html
Programming a Guessing Game - The Rust Programming Language
Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated functions, external crat
rust-book.cs.brown.edu
Setting Up a New Project
$ cargo new guessing_game
$ cd guessing_game
cargo new creates a new cargo project with a name as the argument.
Processing a Guess
use std::io; can be used to process the input.
println! is a macro for printing string to a screen
Storing Values with Variables
let can be used to create a variable.
mut makes the variable to be mutable. Every object in Rust is mutable by default
Associated function is a function that’s implemented on a type. :: is used to describe the associated function.
- ex)
String::new()
Receiving User Input
io::stdin().read_line(&mut guess) can be used to harness user input.
guessis where the value read will be stored and it is referenced by&.&mutreferences and mutates the data.
Handling Potential Failure with Result
Result is used to handle error
Okindicates the operation was successful, and it contains the generated valueErrmeans that the operation failed, and it contains information about how or why the operation failed.- using
expectmethod allows for the handling ofErrwithout needing for program to crash
Printing Values with println! Placeholders
{} can hold value in place.
- a variable can go into the place
println!("You guessed: {guess}");- if the brackets are left blank, a comma-separated list can be followed to go in place of curly brackets
let x = 5; let y = 10; println!("x = {x} and y + 2 = {}", y + 2);
Testing the First Part
cargo run can be used to run the rust file.
Using a Crate to Get More Functionality
Since Rust does not provide a standard library for randomness, rand crate must be used.
library crate: code that is intended to be used in other programs and can’t be executed on its own
binary crate: code that is executable
[dependencies]
rand = "0.8.5"
Adding line above in Cargo.toml file can add dependencies to the programs.
Running cargo build after adding rand crate to the file downloads and compiles the dependencies.
- Running the code once again does nothing because Rust knows that nothing has been changed
**Cargo.lock** file records all the dependencies’ versions used in the program, and this is for reproducibility.
Generating a Random Number
let secret_number = rand::thread_rng().gen_range(1..=100);
gen_range function takes in range as input and returns a random number in that range.
1..=100is used to represent a range of numbers between 1 and 100, inclusive
Comparing the Guess to the Secret Number
by using std::cmp::Ordering type, can be used to get variants Less, Greater, Equal.
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
cmp compares a variable to another variable.
match expression decides what operation to execute based on the patterns of the return value
parse method converts numbers automatically based on Rust’s default inference of value.
- only work on characters that can logically be converted into numbers and so can easily cause errors
Allowing Multiple Guesses with Looping
loop keyword creates an infinite loop. It works the same as while True in Python.
break keyword exits the loop when the statement is executed.
'Rust > The Rust Programming Language' 카테고리의 다른 글
| [The Rust Programming Language] Ch. 3: Common Programming Concepts Variables and Mutability (0) | 2023.11.05 |
|---|