Skip to content

Instantly share code, notes, and snippets.

@techygrrrl
Created October 1, 2022 07:20
Show Gist options
  • Save techygrrrl/69a89f4389c24c7e6382a3b11ca5be6b to your computer and use it in GitHub Desktop.
Save techygrrrl/69a89f4389c24c7e6382a3b11ca5be6b to your computer and use it in GitHub Desktop.
First Rust app (guessing game)
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
authors = ["techygrrrl", "foo <foo@example.com>", "bar <bar@example.com>", "baz <baz@example.com>"]
description = "This is my firrrst Rrrust app!!!!"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.0.7", features = ["derive"] }
rand = "0.8.3"
/*!
# test 2
Hello, world 2!
I am some documentation!
```
println!("Hello, world!");
```
*/
use clap::Parser;
use rand::Rng;
use std::io;
use std::cmp::Ordering;
#[derive(Parser, Debug)]
#[command(
author,
version,
about,
long_about = None,
help_template = "\
{before-help}{name} {version} {author-with-newline}{about-with-newline} \
{usage-heading} {usage} {all-args}{after-help}"
)]
struct Args {
/// Your name
#[arg(short, long)]
name: String,
}
/// A fun game that allows you to guess a numberrr!!!
fn main() {
let args = Args::parse();
println!("Hey, {}, guess the number!", args.name);
let secret_number = rand::thread_rng().gen_range(1..=100);
// println!("The secret number is {secret_number}");
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 = guess.trim().parse().expect("Please type a number!");
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment