add rand, ordering, shadowing, type coercion

This commit is contained in:
LuKe Tidd 2022-12-13 08:53:41 -05:00
parent 915ba1a499
commit 7cbfe8dbc9
Signed by: luke
GPG Key ID: 75D6600BEF4E8E8F
2 changed files with 18 additions and 0 deletions

View File

@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
rand = "0.8.3"

View File

@ -2,10 +2,15 @@
// https://doc.rust-lang.org/std/prelude/index.html // https://doc.rust-lang.org/std/prelude/index.html
// for extras, import them with `use`: // for extras, import them with `use`:
use std::io; use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() { fn main() {
println!("Guess the number!"); println!("Guess the number!");
println!("input your guess"); 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 // vars are immutable by default, change this
// The :: syntax in the ::new line indicates that new is an _associated function_ of the String // The :: syntax in the ::new line indicates that new is an _associated function_ of the String
// a function thats implemented on a type // a function thats 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. // read_line returns a `result` value. result is an enum. Each possible state is a variant.
// Result's variants are Ok and Err // 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}"); 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