From 7cbfe8dbc9987c1e93913262839d18bd90fdfd31 Mon Sep 17 00:00:00 2001 From: Luke Tidd Date: Tue, 13 Dec 2022 08:53:41 -0500 Subject: [PATCH] add rand, ordering, shadowing, type coercion --- guessing_game/Cargo.toml | 1 + guessing_game/src/main.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/guessing_game/Cargo.toml b/guessing_game/Cargo.toml index 78c94fe..cc63f6f 100644 --- a/guessing_game/Cargo.toml +++ b/guessing_game/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +rand = "0.8.3" diff --git a/guessing_game/src/main.rs b/guessing_game/src/main.rs index a0334e5..4583276 100644 --- a/guessing_game/src/main.rs +++ b/guessing_game/src/main.rs @@ -2,10 +2,15 @@ // https://doc.rust-lang.org/std/prelude/index.html // for extras, import them with `use`: use std::io; +use std::cmp::Ordering; +use rand::Rng; fn main() { println!("Guess the number!"); println!("input your guess"); + // ..= is inclusive + let secret_number = rand::thread_rng().gen_range(1..=100); + println!("The secret number is: {secret_number}"); // vars are immutable by default, change this // The :: syntax in the ::new line indicates that new is an _associated function_ of the String // a function that’s implemented on a type @@ -22,5 +27,17 @@ fn main() { // read_line returns a `result` value. result is an enum. Each possible state is a variant. // Result's variants are Ok and Err + // shadowing V + let guess: u32 = guess.trim().parse().expect("please type a number for the love of god"); + // trim removes space and \n println!("you guessed: {guess}"); + // a match expression is made of arms. an arm is a pattern to match and code to run against it. + // switch/case + match guess.cmp(&secret_number) { + Ordering::Less => println!("too small"), + Ordering::Greater => println!("too big"), + Ordering::Equal => println!("you win"), + } } +// cargo doc --open +// generate doc about this code and dependancies