Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
anztrax committed Oct 5, 2018
1 parent e13bfeb commit da6dc48
Show file tree
Hide file tree
Showing 23 changed files with 1,285 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk
/target


.idea
80 changes: 80 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "learnrust"
version = "0.1.0"
authors = ["andrewananta <[email protected]>"]
license = "MIT OR Apache-2.0"

[dependencies]
rand = "0.3.14"


[profile.dev]
opt-level = 0

[profile.release]
opt-level = 3
1 change: 1 addition & 0 deletions hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello gan
79 changes: 79 additions & 0 deletions src/adder/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use ::lessons::Rectangle::Rectangle;
use ::lessons::Guess::Guess;

pub fn add_two(num: i32) -> i32{
num + 2
}

pub fn greeting(name: &str) -> String{
format!("hello, {}", name)
}

#[test]
fn exploration(){
assert_eq!(2 + 2, 4);
}

#[test]
fn larger_can_hold_smaller(){
let larger = Rectangle::new(8, 7);
let smaller = Rectangle::new(5, 1);
assert!(larger.can_hold(&smaller));
}

#[test]
fn smaller_can_not_hold_larger(){
let larger = Rectangle::new(8, 7);
let smaller = Rectangle::new(5, 1);
assert!(!smaller.can_hold(&larger));
}

#[test]
#[ignore]
fn test_greeting_name(){
let result = greeting("carol");
assert!(
result.contains("carol1"),
"Greeting did not contain name, value was `{}`", result
);
}

#[test]
#[should_panic(expected = "assertion failed")]
#[ignore]
fn test_guess_game(){
let guess = Guess::new(0);

}

#[test]
fn add_two_test(){
assert_eq!(4, add_two(2));
}

#[test]
#[ignore]
fn another(){
panic!("Make this test fail !");
}

#[test]
#[ignore]
fn it_works_using_result() -> Result<(), String> {
if 2 + 2 == 5 {
Ok(())
} else {
Err(String::from("two plus two does not equal four"))
}
}

#[test]
fn test_closure(){
let x = 5;
let same_as_y = |y|{ y == x };
let y = 10;
same_as_y(10);
assert_eq!(same_as_y(10), false);

}

101 changes: 101 additions & 0 deletions src/closures/learnClosure.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::thread;
use std::time::Duration;


pub struct Cacher<T> where T: Fn(u32) -> u32{
calculation:T,
value: Option<u32>,
}

impl<T> Cacher<T> where T: Fn(u32) -> u32{
fn new(calculation: T) -> Cacher<T>{
Cacher{
calculation,
value: None
}
}

fn value(&mut self, arg: u32) -> u32{
match self.value{
Some(v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
v
}
}
}
}

///
/// try using documentation comment,
/// this is handy bro
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, my_crate::add_one(5));
/// ```
pub fn simulated_expensive_calculation(intensity: u32){
println!("calculating slowly");
expensive_calculation(100);

let simulated_user_specified_value = 10;
let simulated_random_number = 7;

generate_workout(
simulated_user_specified_value,
simulated_random_number
);
}

pub fn expensive_calculation(intensity: u32) -> u32{
thread::sleep(Duration::from_secs(2));
intensity
}



pub fn generate_workout(intensity: u32, random_number: u32){
let expensive_result2 = expensive_calculation(intensity);
let expensive_result3 = |num: u32| -> u32{
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};

let mut expensive_result = Cacher::new(|num| {
println!("Calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});

//you can skip add type to closure
let example_closure = |x| x;
let x1 = example_closure(String::from("testing gan"));
let x2 = example_closure(String::from("testing gan1 123"));
println!("x1 : {}, x2: {}", x1, x2);


if intensity < 25 {
println!(
"Today, do {} pushups!",
expensive_result.value(intensity)
);
println!(
"Next, do {} situps!",
expensive_result.value(intensity)
);
} else{
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
88 changes: 88 additions & 0 deletions src/closures/learnIterator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#[derive(Debug)]
struct Shoe{
size : u32,
style: String
}

fn shoes_in_my_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe>{
shoes.into_iter()
.filter(|s| s.size == shoe_size)
.collect()
}

//-------------- create custom iterator things
struct Counter{
count: u32
}

impl Counter{
fn new() -> Counter{
Counter{ count: 0 }
}
}

impl Iterator for Counter{
type Item = u32;

fn next(&mut self) -> Option<Self::Item>{
self.count += 1;

if(self.count < 6){
Some(self.count)
}else{
None
}
}
}



//------------- main function
pub fn learnIterator(){
let v1 = vec![1,2,3,4];
let v1_iter = v1.iter();
for item in v1_iter{
println!("v1 iter : {}", item);
}

let v2 = vec![1,2,3,4,5];
let mut v2_iter = v2.iter();
match v2_iter.next(){
Some(value) => println!("v2 iter 0 value : {}", value),
None => println!("none !")
}

//iterator adaptors
let v1: Vec<i32> = vec![1,2,3,4];
let v1_result: Vec<i32> = v1.iter()
.map(|x| x + 1) //this cause warning because didn't consume well
.collect();

println!("v1_result {:?}", v1_result);
find_suitable_shoes();
implement_iterator();
println!("============================");
}

//shoe things
fn find_suitable_shoes(){
let shoes = vec![
Shoe{ size: 10, style: String::from("sneaker")},
Shoe{ size: 20, style: String::from("sneaker")},
Shoe{ size: 22, style: String::from("sneaker")},
];

let in_my_size = shoes_in_my_size(shoes, 20);
println!("in my size {:?}",in_my_size);
}

fn implement_iterator(){
let mut counter = Counter::new();
println!("value : {}", counter.next().unwrap());
let sum: u32 = Counter::new().zip(Counter::new().skip(1))
.map(|(a, b)| a * b )
.filter(|x| x % 3 == 0)
.sum();
println!("value of sum is {}", sum);

}
9 changes: 9 additions & 0 deletions src/closures/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! # Closure
//!
//! `closure` is a collection of utilities to make performing certain
//! calculations more convenient.
pub use closures::learnClosure::Cacher;

pub mod learnClosure;
pub mod learnIterator;
Loading

0 comments on commit da6dc48

Please sign in to comment.