Setting Up a New Project
Create new project with cargo
cargo new --bin guessing-game cd guessing-game
Processing The Code
Setting dependencies in Cargo.toml
[package]
name = "guessing-game"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
Replace the code in src/main.rs
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
//Generating random number from 1 to 100
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("Please input your guess.");
let mut guess = String::new();
//Receiving input
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
//Converting String to Int
let input: u32 = guess
.trim()
.parse()
.expect("Wanted a number");
if secret_number == input {
println!("You are the Best");
} else {
println!("You are wrong");
}
println!("You guessed: {guess}");
}
Testing The Code
Run the code in terminal with command
cd guessing-game
cargo run
Here is the Result
PS C:\guessing-game> cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target\debug\guess.exe`
Guess the number!
Please input your guess.
15
You are wrong
You guessed: 15
Code can be downloaded here
No comments:
Post a Comment