Created
December 5, 2022 01:42
-
-
Save viniciusao/f2008309568e22ec4de20ecafcaf98c3 to your computer and use it in GitHub Desktop.
Common programming concepts in rust (The book).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Some points that made me surprised: | |
// - Variable's states: mutability and immutability. | |
// - Strong typing. | |
// - Statements and expressions, e.g. syntactic scope is an expression. | |
// - Loop labels and break as an expression. | |
use std::io; | |
use rand::Rng; | |
const MAX_INPUT_NUMBER: u8 = u8::MAX; // Constant variable (3.1) and Scalar `u8` data type (3.2). | |
fn main() { | |
loop { // Control Flow (3.5). | |
let mut input = String::new(); // Variable's mutability (3.1). | |
// Statement (3.3). | |
let secret_number = rand::thread_rng().gen_range(0..=MAX_INPUT_NUMBER); | |
println!("Input:"); // Expression (3.3). | |
io::stdin() | |
.read_line(&mut input) | |
.expect("Invalid input."); | |
let input: u8 = match input.trim().parse() { // Variable shadowing and immutability (3.1). | |
Ok(n) => n, | |
Err(_) => { | |
println!( | |
"Input should be a positive number less and equal than {}", | |
MAX_INPUT_NUMBER) | |
; | |
continue | |
} | |
}; | |
match plus_one(input) { | |
Some(_) => println!("Passed integer overflow recheck"), | |
None => { | |
println!("Didn't passed integer overflow recheck by adding one into input value!"); | |
continue | |
} | |
} | |
let winning_output = [input, secret_number]; // Compound data type (3.2). | |
// Ternary and scope expressions (3.5). | |
let did_win = if input == secret_number {true} else {false}; | |
if did_win { // Control flow (3.5). | |
println!( | |
"You won!\nInput number: {} | Secret number: {}", | |
winning_output[0], | |
winning_output[1] | |
); | |
break | |
} else { | |
let [secret_number, _] = winning_output; // Destructuring (3.2). | |
loser_print(secret_number) | |
} | |
} | |
} | |
fn plus_one(n: u8) -> Option<u8> { // Function signature (3.3). | |
n.checked_add(1) // Integer overflow check (3.2). | |
} | |
fn loser_print(secret_number: u8) -> () { // `unit` return annotation type (3.2). | |
println!("You didn't guessed the number {secret_number}! Try again...") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on https://rust-book.cs.brown.edu/ch03-00-common-programming-concepts.html