Programming a Guessing Game
Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit.
Setting Up a New Project
$ cargo new guessing_game_proj && cd guessing_game_proj
Creating binary (application) `guessing_game_proj` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ tree
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
- Look at the generated Cargo.toml file:
[package]
name = "guessing_game_proj"
version = "0.1.0"
edition = "2021"
[dependencies]
- and the src/main.rs as,
fn main() { println!("Hello, world!"); }
- compile and run
$ cargo run
Compiling guessing_game_proj v0.1.0 (/home/alexlai/mdbook-proj/learn-rust-dumindu-madunuwan/src/gussing_game/guessing_game_proj)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.98s
Running `target/debug/guessing_game_proj`
Hello, world!
Processing a Guess
The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess.
- Enter the code in src/main.rs,
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {}", guess); }}