Skip to content

Commit

Permalink
Completes exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
feynmanliang committed Jul 16, 2017
1 parent a87d43d commit ba3d090
Show file tree
Hide file tree
Showing 47 changed files with 122 additions and 89 deletions.
9 changes: 4 additions & 5 deletions error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
// this function to have.
// Scroll down for hints!!!

pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
if name.len() > 0 {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".into())
}
}

Expand All @@ -25,7 +24,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
Some("Hi! My name is Beyoncé".into())
Ok("Hi! My name is Beyoncé".into())
);
}

Expand Down
4 changes: 1 addition & 3 deletions error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();

Ok(qty * cost_per_item + processing_fee)
item_quantity.parse::<i32>().map(|qty| qty * cost_per_item + processing_fee)
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fn main() {
let mut tokens = 100;
let pretend_user_input = "8";

let cost = try!(total_cost(pretend_user_input));
let cost = total_cost(pretend_user_input).expect("Invalid user input!");

if cost > tokens {
println!("You can't afford that many!");
Expand Down
10 changes: 5 additions & 5 deletions error_handling/errorsn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ use std::fmt;
use std::io;

// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut io::BufRead) -> Result<PositiveNonzeroInteger, ???> {
fn read_and_validate(b: &mut io::BufRead) -> Result<PositiveNonzeroInteger, Box<error::Error>>{
let mut line = String::new();
b.read_line(&mut line);
let num: i64 = line.trim().parse();
let answer = PositiveNonzeroInteger::new(num);
answer
try!(b.read_line(&mut line));
let num: i64 = try!(line.trim().parse());
let answer = try!(PositiveNonzeroInteger::new(num));
Ok(answer)
}

// This is a test helper function that turns a &str into a BufReader.
Expand Down
10 changes: 6 additions & 4 deletions error_handling/option1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
fn main() {
let mut list = vec![3];

let last = list.pop().unwrap();
println!("The last item in the list is {:?}", last);
if let Some(last) = list.pop() {
println!("The last item in the list is {:?}", last);
}

let second_to_last = list.pop().unwrap();
println!("The second-to-last item in the list is {:?}", second_to_last);
if let Some(second_to_last) = list.pop() {
println!("The second-to-last item in the list is {:?}", second_to_last);
}
}


Expand Down
6 changes: 5 additions & 1 deletion error_handling/result1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ enum CreationError {

impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
Ok(PositiveNonzeroInteger(value as u64))
match value {
0 => Err(CreationError::Zero),
_ if value < 0 => Err(CreationError::Negative),
_ => Ok(PositiveNonzeroInteger(value as u64))
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion ex1.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Make me compile!

fn main() {
println();
println!();
}
2 changes: 1 addition & 1 deletion ex2.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Make me compile!

fn something() -> String {
"hi!"
"hi!".into()
}

fn main() {
Expand Down
1 change: 1 addition & 0 deletions ex3.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Make me compile!

#[derive(Debug)]
struct Foo {
capacity: i32,
}
Expand Down
2 changes: 1 addition & 1 deletion ex4.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Make me compile!

fn something() -> Result<i32, std::num::ParseIntError> {
let x:i32 = "3".parse();
let x:i32 = try!("3".parse());
Ok(x * 4)
}

Expand Down
10 changes: 5 additions & 5 deletions ex5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ enum Reaction<'a> {
Happy(&'a str),
}

fn express(sentiment: Reaction) {
match sentiment {
fn express(sentiment: &Reaction) {
match *sentiment {
Reaction::Sad(s) => println!(":( {}", s),
Reaction::Happy(s) => println!(":) {}", s),
}
}

fn main () {
let x = Reaction::Happy("It's a great day for Rust!");
express(x);
express(x);
express(&x);
express(&x);
let y = Reaction::Sad("This code doesn't compile yet.");
express(y);
express(&y);
}
2 changes: 2 additions & 0 deletions functions/functions1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ fn main() {
call_me();
}

fn call_me() { }




Expand Down
2 changes: 1 addition & 1 deletion functions/functions2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ fn main() {
call_me(3);
}

fn call_me(num) {
fn call_me(num: i32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
Expand Down
2 changes: 1 addition & 1 deletion functions/functions3.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Make me compile! Scroll down for hints :)

fn main() {
call_me();
call_me(10);
}

fn call_me(num: i32) {
Expand Down
2 changes: 1 addition & 1 deletion functions/functions4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ fn main() {
println!("Your sale price is {}", sale_price(original_price));
}

fn sale_price(price: i32) -> {
fn sale_price(price: i32) -> i32 {
if is_even(price) {
price - 10
} else {
Expand Down
2 changes: 1 addition & 1 deletion functions/functions5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ fn main() {
}

fn square(num: i32) -> i32 {
num * num;
num * num
}


Expand Down
5 changes: 5 additions & 0 deletions if/if1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ pub fn bigger(a: i32, b:i32) -> i32 {
// - another function call
// - additional variables
// Scroll down for hints.
if a > b {
a
} else {
b
}
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion macros/macros1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ macro_rules! my_macro {
}

fn main() {
my_macro();
my_macro!();
}


Expand Down
9 changes: 5 additions & 4 deletions macros/macros2.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
// Make me compile! Scroll down for hints :)

fn main() {
my_macro!();
}

macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}

fn main() {
my_macro!();
}





Expand Down
1 change: 1 addition & 0 deletions macros/macros3.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Make me compile, without taking the macro out of the module! Scroll down for hints :)

#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
Expand Down
2 changes: 1 addition & 1 deletion macros/macros4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
Expand Down
2 changes: 1 addition & 1 deletion modules/modules1.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Make me compile! Scroll down for hints :)

mod sausage_factory {
fn make_sausage() {
pub fn make_sausage() {
println!("sausage!");
}
}
Expand Down
6 changes: 3 additions & 3 deletions modules/modules2.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Make me compile! Scroll down for hints :)

mod us_presidential_frontrunners {
use self::democrats::HILLARY_CLINTON as democrat;
use self::republicans::DONALD_TRUMP as republican;
pub use self::democrats::HILLARY_CLINTON as democrat;
pub use self::republicans::DONALD_TRUMP as republican;

mod democrats {
pub const HILLARY_CLINTON: &'static str = "Hillary Clinton";
Expand Down Expand Up @@ -44,4 +44,4 @@ fn main() {
// each constant.
// One more hint: I wish the compiler error, instead of saying "unresolved name
// `us_presidential_frontrunners::democrat`", could say "constant
// `us_presidential_frontrunners::democrat` is private"!
// `us_presidential_frontrunners::democrat` is private"!
2 changes: 1 addition & 1 deletion move_semantics/move_semantics1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
pub fn main() {
let vec0 = Vec::new();

let vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(vec0);

println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

Expand Down
6 changes: 3 additions & 3 deletions move_semantics/move_semantics2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
pub fn main() {
let vec0 = Vec::new();

let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec(&vec0);

// Do not change the following line!
println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0);
Expand All @@ -14,8 +14,8 @@ pub fn main() {

}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
fn fill_vec(vec: &Vec<i32>) -> Vec<i32> {
let mut vec = vec.clone();

vec.push(22);
vec.push(44);
Expand Down
2 changes: 1 addition & 1 deletion move_semantics/move_semantics3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub fn main() {

}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);
Expand Down
8 changes: 3 additions & 5 deletions move_semantics/move_semantics4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
// freshly created vector from fill_vec to its caller. Scroll for hints!

pub fn main() {
let vec0 = Vec::new();

let mut vec1 = fill_vec(vec0);
let mut vec1 = fill_vec();

println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

Expand All @@ -15,8 +13,8 @@ pub fn main() {

}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
fn fill_vec() -> Vec<i32> {
let mut vec = Vec::new();

vec.push(22);
vec.push(44);
Expand Down
2 changes: 1 addition & 1 deletion primitive_types/primitive_types1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fn main() {
println!("Good morning!");
}

let // Finish the rest of this line like the example! Or make it be false!
let is_evening = !is_morning; // Finish the rest of this line like the example! Or make it be false!
if is_evening {
println!("Good evening!");
}
Expand Down
2 changes: 1 addition & 1 deletion primitive_types/primitive_types2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
println!("Neither alphabetic nor numeric!");
}

let // Finish this line like the example! What's your favorite character?
let your_character = 'b';// Finish this line like the example! What's your favorite character?
// Try a letter, try a number, try a special character, try a character
// from a different language than your own, try an emoji!
if your_character.is_alphabetic() {
Expand Down
6 changes: 3 additions & 3 deletions primitive_types/primitive_types3.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Create an array with at least 100 elements in it where the ??? is.
// Create an array with at least 100 elements in it where the ??? is.
// Scroll down for hints!

fn main() {
let a = ???
let a = [0; 100];

if a.len() >= 100 {
println!("Wow, that's a big array!");
Expand Down Expand Up @@ -37,7 +37,7 @@ fn main() {



// There's a shorthand to initialize Arrays with a certain size that does not
// There's a shorthand to initialize Arrays with a certain size that does not
// require you to type in 100 items (but you certainly can if you want!)
// Check out the Primitive Types -> Arrays section of the book:
// http://doc.rust-lang.org/stable/book/primitive-types.html#arrays
Expand Down
2 changes: 1 addition & 1 deletion primitive_types/primitive_types4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
fn main() {
let a = [1, 2, 3, 4, 5];

let nice_slice = ???
let nice_slice = &a[1..4];

if nice_slice == [2, 3, 4] {
println!("Nice slice!");
Expand Down
2 changes: 1 addition & 1 deletion primitive_types/primitive_types5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

fn main() {
let cat = ("Furry McFurson", 3.5);
let /* your pattern here */ = cat;
let (name, age) = cat;

println!("{} is {} years old.", name, age);
}
Expand Down
Loading

0 comments on commit ba3d090

Please sign in to comment.