use std::{thread, time::Duration};
use rust_closures_examples::kinds::SecondryColor;
#[derive(Debug, PartialEq, Clone, Copy)]
enum ShirtColor {
Red,
Blue,
}
struct Inventory {
shirts: Vec<ShirtColor>,
}
impl Inventory {
fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
user_preference.unwrap_or_else(|| self.most_stocked())
}
fn most_stocked(&self) -> ShirtColor {
let mut num_red = 0;
let mut num_blue = 0;
for color in &self.shirts {
match color {
ShirtColor::Blue => num_blue += 1,
ShirtColor::Red => num_red += 1,
}
}
if num_red > num_blue {
ShirtColor::Red
} else {
ShirtColor::Blue
}
}
}
fn main() {
let expensive_closure = |num: u32| -> u32 {
println!("Calculating Slowly!!!...");
thread::sleep(Duration::from_secs(3));
num
};
println!("{}", expensive_closure(5));
let v1 = add_v1(2);
println!("The value of v1 is: {}", v1);
borrow_immutable();
borrow_mutable();
taking_ownership();
let mut list = [
Rectangle {
width: 3,
height: 2,
},
Rectangle {
width: 2,
height: 3,
},
Rectangle {
width: 1,
height: 5,
},
];
let mut sort_operations = vec![];
let value = String::from("by key called");
list.sort_by_key(|r| {
sort_operations.push(value.clone());
r.width
});
let mut num_operations = 0;
list.sort_by_key(|r| {
num_operations += 1;
r.width
});
println!("{:?} sorted in {num_operations} operations", list);
use rust_closures_examples::kinds::PrimaryColor;
use rust_closures_examples::utils::mix;
let red = PrimaryColor::Red;
println!("The color is: {:?}", red);
let yellow = SecondryColor::Orange;
mix(red, yellow);
}
fn add_v1(x: u32) -> u32 {
x + 1
}
fn borrow_immutable() {
let list = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let only_borrows = || println!("From closure {:?}", list);
only_borrows();
println!("after calling closure");
println!("{:?}", list);
}
fn borrow_mutable() {
let mut list = vec![1, 2, 3];
println!("Before defining closure: {:?}", list);
let mut borrow_mut = || list.push(4);
borrow_mut();
println!("after defining closure: {:?}", list);
}
fn taking_ownership() {
let list: Vec<i32> = vec![1, 2];
print!("before defining closure: {:?}", list);
thread::spawn(move || println!("from thread: {:?}", list))
.join()
.unwrap();
}
#[derive(Debug)]
enum Option<T> {
Some(T),
None,
}
impl<T> Option<T> {
fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T,
{
match self {
Option::Some(x) => x,
Option::None => f(),
}
}
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}