Created
January 20, 2020 16:38
-
-
Save abhayarawal/c902a2ef953fa679abf2186b4195675a to your computer and use it in GitHub Desktop.
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
use std::ops::Deref; | |
use std::rc::Rc; | |
#[derive(PartialEq, Debug, Clone)] | |
struct Shoe { | |
size: u32, | |
style: String, | |
} | |
struct MyBox<T>(T); | |
impl<T> MyBox<T> { | |
fn new(t: T) -> MyBox<T> { | |
MyBox(t) | |
} | |
} | |
impl<T> Deref for MyBox<T> { | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
&self.0 | |
} | |
} | |
fn select_size(shoes: &Vec<Shoe>, size: u32) -> Vec<&Shoe> { | |
shoes | |
.into_iter() | |
.filter(|s| s.size == size) | |
.collect::<Vec<&Shoe>>() | |
} | |
fn main() { | |
let b = MyBox::new(19); | |
println!("box: {}", *b); | |
let mut a = Rc::new(10); | |
let mut a3 = Rc::get_mut(&mut a).unwrap(); | |
*a3 = 100; | |
let a1 = Rc::clone(&a); | |
let a2 = Rc::clone(&a); | |
println!("Rc: {}, refs: {}", a1, Rc::strong_count(&a)); | |
let v1 = vec![1, 2, 3]; | |
let v2 = v1.iter().map(|n| n * *n).collect::<Vec<i32>>(); | |
println!("{:?}", v2); | |
println!( | |
"{:?}", | |
(1..=10) | |
.collect::<Vec<u32>>() | |
.iter() | |
.fold(0, |acc, n| acc + *n) | |
); | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn filters_by_size() { | |
let shoes = vec![ | |
Shoe { | |
size: 10, | |
style: String::from("Allbirds"), | |
}, | |
Shoe { | |
size: 13, | |
style: String::from("Ultraboost"), | |
}, | |
]; | |
let in_my_size = select_size(&shoes, 10); | |
println!("{:?}", in_my_size); | |
assert_eq!( | |
in_my_size, | |
vec![&Shoe { | |
size: 10, | |
style: String::from("Allbirds") | |
}] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment