--- main.rs.old 2022-04-24 04:40:47.371994619 -0400
+++
main.rs 2022-04-24 04:40:01.011994637 -0400
@@ -1,8 +1,13 @@
use std::io;
+use rand::Rng;
fn main() {
println!("Guess the number!");
+ let secret_number = rand::thread_rng().gen_range(1..101);
+
+ println!("The secret number is: {}", secret_number);
+
println!("Please input your guess.");
let mut guess = String::new();
rand::Rng adds random number generator traits. without it, gen_range() does not appear on thread_rng().
rand::thread_rng() is a thread local OS-seeded prng.
1..101 is a range expression of [1,101). it is equivalent here to 1..100 which is [1,100].
cargo doc --open will show documentation of the rand and all other project crates.
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
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 = 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;
}
}
}
}
rust lets you shadow variables in the same scope, retyping them, optionally based on their previous values
String::trim removes the enter character read_line preserved
String::parse returns a number
match {} is a switch or select statement that provides for patterns and use as an expression
rust infers the type of secret_number from the type of guess
std::cmp::Ordering is an enum type return by the .cmp method.
Homework:
1. Implement and run the guessing example.
2. Make a rust project that uses std::io to generate a .jl julia script that performs and outputs the result of an arithmetic calculation.
julia: see other thread with similar name