diff --git a/exercises/advanced_errors/advanced_errs1.rs b/exercises/advanced_errors/advanced_errs1.rs index 4bc7b635..6dda9fb7 100644 --- a/exercises/advanced_errors/advanced_errs1.rs +++ b/exercises/advanced_errors/advanced_errs1.rs @@ -24,12 +24,18 @@ impl From for ParsePosNonzeroError { fn from(e: CreationError) -> Self { // TODO: complete this implementation so that the `?` operator will // work for `CreationError` + Self::Creation(e) } } // TODO: implement another instance of the `From` trait here so that the // `?` operator will work in the other place in the `FromStr` // implementation below. +impl From for ParsePosNonzeroError { + fn from(e: ParseIntError) -> Self { + Self::ParseInt(e) + } +} // Don't change anything below this line. diff --git a/exercises/advanced_errors/advanced_errs2.rs b/exercises/advanced_errors/advanced_errs2.rs index d9d44d06..5204c38a 100644 --- a/exercises/advanced_errors/advanced_errs2.rs +++ b/exercises/advanced_errors/advanced_errs2.rs @@ -47,9 +47,14 @@ impl From for ParseClimateError { impl From for ParseClimateError { fn from(e: ParseFloatError) -> Self { // TODO: Complete this function + Self::ParseFloat(e) } } +impl std::error::Error for ParseClimateError { + +} + // TODO: Implement a missing trait so that `main()` below will compile. It // is not necessary to implement any methods inside the missing trait. @@ -63,7 +68,10 @@ impl Display for ParseClimateError { use ParseClimateError::*; match self { NoCity => write!(f, "no city name"), + BadLen => write!(f, "incorrect number of fields"), + Empty => write!(f, "empty input"), ParseFloat(e) => write!(f, "error parsing temperature: {}", e), + ParseInt(e) => write!(f, "error parsing year: {}", e), _ => write!(f, "unhandled error!"), } } @@ -90,11 +98,19 @@ impl FromStr for Climate { // cases. fn from_str(s: &str) -> Result { let v: Vec<_> = s.split(',').collect(); - let (city, year, temp) = match &v[..] { + let (city, yr, temp) = match &v[..] { [city, year, temp] => (city.to_string(), year, temp), + [""] => return Err(ParseClimateError::Empty), _ => return Err(ParseClimateError::BadLen), }; - let year: u32 = year.parse()?; + if city.is_empty() { + return Err(ParseClimateError::NoCity); + } + let year: u32; + match yr.parse::() { + Ok(y) => year = y, + Err(e) => return Err(ParseClimateError::ParseInt(e)) + } let temp: f32 = temp.parse()?; Ok(Climate { city, year, temp }) } diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index 37af9ed0..352c4e16 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -6,7 +6,7 @@ fn main() { let mut res = 42; let option = Some(12); - for x in option { + if let Some(x) = option { res += x; } println!("{}", res); diff --git a/exercises/collections/hashmap1.rs b/exercises/collections/hashmap1.rs index 64b5a7f3..e4dbf8b4 100644 --- a/exercises/collections/hashmap1.rs +++ b/exercises/collections/hashmap1.rs @@ -16,12 +16,14 @@ use std::collections::HashMap; fn fruit_basket() -> HashMap { - let mut basket = // TODO: declare your hash map here. + let mut basket = HashMap::new(); // Two bananas are already given for you :) basket.insert(String::from("banana"), 2); // TODO: Put more fruits in your basket here. + basket.insert(String::from("apple"), 2); + basket.insert(String::from("peach"), 3); basket } diff --git a/exercises/collections/hashmap2.rs b/exercises/collections/hashmap2.rs index 0abe19ab..95c9ffdf 100644 --- a/exercises/collections/hashmap2.rs +++ b/exercises/collections/hashmap2.rs @@ -38,6 +38,7 @@ fn fruit_basket(basket: &mut HashMap) { // TODO: Put new fruits if not already present. Note that you // are not allowed to put any type of fruit that's already // present! + basket.entry(fruit).or_insert(1); } } diff --git a/exercises/collections/vec1.rs b/exercises/collections/vec1.rs index b144fb94..88035b73 100644 --- a/exercises/collections/vec1.rs +++ b/exercises/collections/vec1.rs @@ -8,7 +8,7 @@ fn array_and_vec() -> ([i32; 4], Vec) { let a = [10, 20, 30, 40]; // a plain array - let v = // TODO: declare your vector here with the macro for vectors + let v = vec![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors (a, v) } diff --git a/exercises/collections/vec2.rs b/exercises/collections/vec2.rs index 6595e401..da31812e 100644 --- a/exercises/collections/vec2.rs +++ b/exercises/collections/vec2.rs @@ -13,6 +13,7 @@ fn vec_loop(mut v: Vec) -> Vec { for i in v.iter_mut() { // TODO: Fill this up so that each element in the Vec `v` is // multiplied by 2. + *i *= 2 } // At this point, `v` should be equal to [4, 8, 12, 16, 20]. diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index 84f4a60c..68325668 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -6,13 +6,15 @@ // Obtain the number of bytes (not characters) in the given argument // Add the AsRef trait appropriately as a trait bound -fn byte_counter(arg: T) -> usize { +fn byte_counter(arg: T) -> usize + where T: AsRef { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument // Add the AsRef trait appropriately as a trait bound -fn char_counter(arg: T) -> usize { +fn char_counter(arg: T) -> usize + where T: AsRef { arg.as_ref().chars().count() } diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index 9d84174d..90e0dc91 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -37,6 +37,24 @@ impl Default for Person { impl From<&str> for Person { fn from(s: &str) -> Person { + let v: Vec<_> = s.split(",").collect(); + // println!("{:?}", v); + let (name, age) = match &v[..] { + ["", _] => return Default::default(), + [_, ""] => return Default::default(), + [name, age] => (name.to_string(), age), + _ => return Default::default() + }; + + let age: usize = match age.parse() { + Ok(age) => age, + _ => return Default::default() + }; + + Self { + name, + age + } } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index ece0b3cf..e9c60e07 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -41,6 +41,22 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + let v: Vec<_> = s.split(",").collect(); + let (name, age) = match &v[..] { + [""] => return Err(ParsePersonError::Empty), + ["", _] => return Err(ParsePersonError::NoName), + [name, age] => (name.to_string(), age), + _ => return Err(ParsePersonError::BadLen) + }; + + let age: usize = match age.parse() { + Ok(age) => age, + Err(e) => return Err(ParsePersonError::ParseInt(e)) + }; + + Ok(Self { + name, age + }) } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index b8ec4455..efd095e2 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -36,6 +36,24 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + let red = match u8::try_from(tuple.0) { + Ok(red) => red, + _ => return Err(Self::Error::IntConversion), + }; + + let green = match u8::try_from(tuple.1) { + Ok(green) => green, + _ => return Err(Self::Error::IntConversion), + }; + + let blue = match u8::try_from(tuple.2) { + Ok(blue) => blue, + _ => return Err(Self::Error::IntConversion), + }; + + Ok(Self { + red, green, blue + }) } } @@ -43,6 +61,7 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + Self::try_from((arr[0], arr[1], arr[2])) } } @@ -50,6 +69,11 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() != 3 { + return Err(Self::Error::BadLen); + } + + Self::try_from((slice[0], slice[1], slice[2])) } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 821309ec..5aabe4ad 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -9,7 +9,7 @@ fn average(values: &[f64]) -> f64 { let total = values.iter().fold(0.0, |a, b| a + b); - total / values.len() + total / (values.len() as f64) } fn main() { diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index a2223d33..9301c20a 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -6,6 +6,10 @@ #[derive(Debug)] enum Message { // TODO: define a few types of messages as used below + Quit, + Echo, + Move, + ChangeColor, } fn main() { diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index ec32d952..c8d56671 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -6,6 +6,10 @@ #[derive(Debug)] enum Message { // TODO: define the different variants used below + Move {x: i32, y: i32}, + Echo (String), + ChangeColor (i32, i32, i32), + Quit, } impl Message { diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index 178b40c4..27455fb6 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -2,11 +2,15 @@ // Address all the TODOs to make the tests pass! // I AM NOT DONE - +#[derive(Debug)] enum Message { // TODO: implement the message variant types based on their usage below + ChangeColor((u8, u8, u8)), + Echo(String), + Move(Point), + Quit, } - +#[derive(Debug)] struct Point { x: u8, y: u8, @@ -37,6 +41,20 @@ impl State { fn process(&mut self, message: Message) { // TODO: create a match expression to process the different message variants + match message { + Message::ChangeColor((x, y, z)) => { + self.color = (x, y, z); + }, + Message::Move(p) => { + self.position = p; + }, + Message::Quit => { + self.quit = true; + }, + Message::Echo(s) => { + println!("{}", s); + } + } } } diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 9c24d85d..9a478b60 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -8,12 +8,12 @@ // I AM NOT DONE -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { 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.".to_string()) } } @@ -28,7 +28,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()) ); } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index aad3a93f..444ca4d6 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -23,9 +23,12 @@ use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::(); - - Ok(qty * cost_per_item + processing_fee) + match item_quantity.parse::() { + Ok(qty) => { + Ok(qty * cost_per_item + processing_fee) + }, + e => e + } } #[cfg(test)] diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index 460ac5c4..6972fb63 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -12,7 +12,7 @@ fn main() { let mut tokens = 100; let pretend_user_input = "8"; - let cost = total_cost(pretend_user_input)?; + let cost = total_cost(pretend_user_input).unwrap(); if cost > tokens { println!("You can't afford that many!"); @@ -25,7 +25,8 @@ fn main() { pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::()?; - - Ok(qty * cost_per_item + processing_fee) + match item_quantity.parse::() { + Ok(qty) => Ok(qty * cost_per_item + processing_fee), + e => e + } } diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index 0685c374..d828dcd5 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -14,7 +14,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { - Ok(PositiveNonzeroInteger(value as u64)) + if value < 0 { + Err(CreationError::Negative) + } else if value == 0 { + Err(CreationError::Zero) + } else { + Ok(PositiveNonzeroInteger(value as u64)) + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 365a8691..a7499f41 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -11,7 +11,7 @@ use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), ParseIntError> { +fn main() -> Result<(), Box> { let pretend_user_input = "42"; let x: i64 = pretend_user_input.parse()?; println!("output={:?}", PositiveNonzeroInteger::new(x)?); diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index 0f6b27a6..772e0f35 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -24,6 +24,9 @@ impl ParsePosNonzeroError { ParsePosNonzeroError::Creation(err) } // TODO: add another error conversion function here. + fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError { + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) @@ -31,9 +34,15 @@ fn parse_pos_nonzero(s: &str) { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); - PositiveNonzeroInteger::new(x) - .map_err(ParsePosNonzeroError::from_creation) + match s.parse() { + Ok(x) => { + match PositiveNonzeroInteger::new(x) { + Ok(pni) => Ok(pni), + Err(e) => Err(ParsePosNonzeroError::from_creation(e)) + } + }, + Err(e) => Err(ParsePosNonzeroError::from_parseint(e)) + } } // Don't change anything below this line. diff --git a/exercises/functions/functions1.rs b/exercises/functions/functions1.rs index 31125278..176aed97 100644 --- a/exercises/functions/functions1.rs +++ b/exercises/functions/functions1.rs @@ -3,6 +3,10 @@ // I AM NOT DONE +fn call_me() { + +} + fn main() { call_me(); } diff --git a/exercises/functions/functions2.rs b/exercises/functions/functions2.rs index 5721a172..d493ca65 100644 --- a/exercises/functions/functions2.rs +++ b/exercises/functions/functions2.rs @@ -7,7 +7,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); } diff --git a/exercises/functions/functions3.rs b/exercises/functions/functions3.rs index ed5f839f..18ef5436 100644 --- a/exercises/functions/functions3.rs +++ b/exercises/functions/functions3.rs @@ -4,7 +4,7 @@ // I AM NOT DONE fn main() { - call_me(); + call_me(3); } fn call_me(num: u32) { diff --git a/exercises/functions/functions4.rs b/exercises/functions/functions4.rs index 58637e4c..ac3b8ef9 100644 --- a/exercises/functions/functions4.rs +++ b/exercises/functions/functions4.rs @@ -11,7 +11,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 { diff --git a/exercises/functions/functions5.rs b/exercises/functions/functions5.rs index d22aa6c8..d4ceceed 100644 --- a/exercises/functions/functions5.rs +++ b/exercises/functions/functions5.rs @@ -9,5 +9,5 @@ fn main() { } fn square(num: i32) -> i32 { - num * num; + num * num } diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index f93e64a0..0c234aff 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -6,6 +6,6 @@ // I AM NOT DONE fn main() { - let mut shopping_list: Vec = Vec::new(); + let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 1501529c..2225860d 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -5,12 +5,12 @@ // I AM NOT DONE -struct Wrapper { - value: u32, +struct Wrapper { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl Wrapper { + pub fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/generics/generics3.rs b/exercises/generics/generics3.rs index 64dd9bc1..f3dc9988 100644 --- a/exercises/generics/generics3.rs +++ b/exercises/generics/generics3.rs @@ -12,13 +12,13 @@ // I AM NOT DONE -pub struct ReportCard { - pub grade: f32, +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { format!("{} ({}) - achieved a grade of {}", &self.student_name, &self.student_age, &self.grade) @@ -46,7 +46,7 @@ mod tests { fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+", student_name: "Gary Plotter".to_string(), student_age: 11, }; diff --git a/exercises/if/if1.rs b/exercises/if/if1.rs index 90867545..9efe170c 100644 --- a/exercises/if/if1.rs +++ b/exercises/if/if1.rs @@ -8,6 +8,11 @@ pub fn bigger(a: i32, b: i32) -> i32 { // - another function call // - additional variables // Execute `rustlings hint if1` for hints + if a > b { + a + } else { + b + } } // Don't mind this for now :) diff --git a/exercises/if/if2.rs b/exercises/if/if2.rs index 80effbdf..4c1c1ee6 100644 --- a/exercises/if/if2.rs +++ b/exercises/if/if2.rs @@ -9,8 +9,10 @@ pub fn fizz_if_foo(fizzish: &str) -> &str { if fizzish == "fizz" { "foo" + } else if fizzish == "fuzz" { + "bar" } else { - 1 + "baz" } } diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs index ed0dac85..2ffe5202 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -3,6 +3,7 @@ // I AM NOT DONE +#[macro_export] macro_rules! my_macro { () => { println!("Check out my macro!"); @@ -10,5 +11,5 @@ macro_rules! my_macro { } fn main() { - my_macro(); + my_macro!(); } diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index d0be1236..bd8e5f1a 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -7,6 +7,7 @@ fn main() { my_macro!(); } +#[macro_export] macro_rules! my_macro { () => { println!("Check out my macro!"); diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs index 93a43113..17cb8e3f 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -4,6 +4,7 @@ // I AM NOT DONE +#[macro_use] mod macros { macro_rules! my_macro { () => { diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 3a748078..1b550f43 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -6,10 +6,10 @@ macro_rules! my_macro { () => { println!("Check out my macro!"); - } + }; ($val:expr) => { println!("Look at this other macro: {}", $val); - } + }; } fn main() { diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 1a2bd0dd..f74b4b1e 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -9,7 +9,7 @@ mod sausage_factory { String::from("Ginger") } - fn make_sausage() { + pub fn make_sausage() { get_secret_recipe(); println!("sausage!"); } diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs index 87f0c458..7b286719 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -8,8 +8,8 @@ mod delicious_snacks { // TODO: Fix these use statements - use self::fruits::PEAR as ??? - use self::veggies::CUCUMBER as ??? + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; mod fruits { pub const PEAR: &'static str = "Pear"; diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index 8eed77df..96ebf65e 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,7 +8,7 @@ // I AM NOT DONE // TODO: Complete this use statement -use ??? +use std::time::{ SystemTime, UNIX_EPOCH }; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/move_semantics/move_semantics1.rs b/exercises/move_semantics/move_semantics1.rs index e2f5876d..acec55a6 100644 --- a/exercises/move_semantics/move_semantics1.rs +++ b/exercises/move_semantics/move_semantics1.rs @@ -4,9 +4,9 @@ // I AM NOT DONE fn main() { - let vec0 = Vec::new(); + let mut vec0 = Vec::new(); - let vec1 = fill_vec(vec0); + let mut vec1 = fill_vec(vec0); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); @@ -15,8 +15,7 @@ fn main() { println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; +fn fill_vec(mut vec: Vec) -> Vec { vec.push(22); vec.push(44); diff --git a/exercises/move_semantics/move_semantics2.rs b/exercises/move_semantics/move_semantics2.rs index bd21fbb7..48587254 100644 --- a/exercises/move_semantics/move_semantics2.rs +++ b/exercises/move_semantics/move_semantics2.rs @@ -7,7 +7,7 @@ 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); @@ -17,8 +17,8 @@ fn main() { println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; +fn fill_vec(vec: &Vec) -> Vec { + let mut vec = vec.clone(); vec.push(22); vec.push(44); diff --git a/exercises/move_semantics/move_semantics3.rs b/exercises/move_semantics/move_semantics3.rs index 43fef74f..f611b329 100644 --- a/exercises/move_semantics/move_semantics3.rs +++ b/exercises/move_semantics/move_semantics3.rs @@ -6,7 +6,7 @@ // I AM NOT DONE fn main() { - let vec0 = Vec::new(); + let mut vec0 = Vec::new(); let mut vec1 = fill_vec(vec0); @@ -17,7 +17,7 @@ fn main() { println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { +fn fill_vec(mut vec: Vec) -> Vec { vec.push(22); vec.push(44); vec.push(66); diff --git a/exercises/move_semantics/move_semantics4.rs b/exercises/move_semantics/move_semantics4.rs index 2a23c710..6be3c468 100644 --- a/exercises/move_semantics/move_semantics4.rs +++ b/exercises/move_semantics/move_semantics4.rs @@ -7,9 +7,8 @@ // I AM NOT DONE 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); @@ -20,7 +19,7 @@ fn main() { // `fill_vec()` no longer takes `vec: Vec` as argument fn fill_vec() -> Vec { - let mut vec = vec; + let mut vec = Vec::new(); vec.push(22); vec.push(44); diff --git a/exercises/move_semantics/move_semantics5.rs b/exercises/move_semantics/move_semantics5.rs index 1afe16c5..5f6b1e19 100644 --- a/exercises/move_semantics/move_semantics5.rs +++ b/exercises/move_semantics/move_semantics5.rs @@ -8,8 +8,8 @@ fn main() { let mut x = 100; let y = &mut x; - let z = &mut x; *y += 100; + let z = &mut x; *z += 1000; assert_eq!(x, 1200); } diff --git a/exercises/option/option1.rs b/exercises/option/option1.rs index 602ff1a9..85e8b630 100644 --- a/exercises/option/option1.rs +++ b/exercises/option/option1.rs @@ -9,15 +9,15 @@ fn print_number(maybe_number: Option) { } fn main() { - print_number(13); - print_number(99); + print_number(Some(13)); + print_number(Some(99)); - let mut numbers: [Option; 5]; + let mut numbers: [Option; 5] = [None; 5]; for iter in 0..5 { let number_to_add: u16 = { ((iter * 1235) + 2) / (4 * 16) }; - numbers[iter as usize] = number_to_add; + numbers[iter as usize] = Some(number_to_add); } } diff --git a/exercises/option/option2.rs b/exercises/option/option2.rs index c6b83ece..1592072d 100644 --- a/exercises/option/option2.rs +++ b/exercises/option/option2.rs @@ -6,7 +6,7 @@ fn main() { let optional_word = Some(String::from("rustlings")); // TODO: Make this an if let statement whose value is "Some" type - word = optional_word { + if let Some(word) = optional_word { println!("The word is: {}", word); } else { println!("The optional word doesn't contain anything"); @@ -19,7 +19,7 @@ fn main() { // TODO: make this a while let statement - remember that vector.pop also adds another layer of Option // You can stack `Option`'s into while let and if let - integer = optional_integers_vec.pop() { + while let Some(Some(integer)) = optional_integers_vec.pop() { println!("current value: {}", integer); } } diff --git a/exercises/option/option3.rs b/exercises/option/option3.rs index 045d2acb..c37ce534 100644 --- a/exercises/option/option3.rs +++ b/exercises/option/option3.rs @@ -11,9 +11,14 @@ struct Point { fn main() { let y: Option = Some(Point { x: 100, y: 200 }); - match y { + match y.as_ref() { Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), _ => println!("no match"), } + + match y { + Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y), + _ => println!("no match"), + } y; // Fix without deleting this line. } diff --git a/exercises/primitive_types/primitive_types1.rs b/exercises/primitive_types/primitive_types1.rs index 09121392..ad229e31 100644 --- a/exercises/primitive_types/primitive_types1.rs +++ b/exercises/primitive_types/primitive_types1.rs @@ -12,7 +12,7 @@ fn main() { println!("Good morning!"); } - let // Finish the rest of this line like the example! Or make it be false! + let is_evening = true; // Finish the rest of this line like the example! Or make it be false! if is_evening { println!("Good evening!"); } diff --git a/exercises/primitive_types/primitive_types2.rs b/exercises/primitive_types/primitive_types2.rs index 6576a4d5..ceb0cd31 100644 --- a/exercises/primitive_types/primitive_types2.rs +++ b/exercises/primitive_types/primitive_types2.rs @@ -1,4 +1,3 @@ -// primitive_types2.rs // Fill in the rest of the line that has code missing! // No hints, there's no tricks, just get used to typing these :) @@ -16,7 +15,7 @@ fn main() { println!("Neither alphabetic nor numeric!"); } - let // Finish this line like the example! What's your favorite character? + let your_character = '😊'; // 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() { diff --git a/exercises/primitive_types/primitive_types3.rs b/exercises/primitive_types/primitive_types3.rs index aaa518be..ea56b7ae 100644 --- a/exercises/primitive_types/primitive_types3.rs +++ b/exercises/primitive_types/primitive_types3.rs @@ -5,7 +5,7 @@ // I AM NOT DONE fn main() { - let a = ??? + let a = [1; 100]; if a.len() >= 100 { println!("Wow, that's a big array!"); diff --git a/exercises/primitive_types/primitive_types4.rs b/exercises/primitive_types/primitive_types4.rs index 10b553e9..f62477a3 100644 --- a/exercises/primitive_types/primitive_types4.rs +++ b/exercises/primitive_types/primitive_types4.rs @@ -8,7 +8,7 @@ fn slice_out_of_array() { let a = [1, 2, 3, 4, 5]; - let nice_slice = ??? + let nice_slice = &a[1..4]; assert_eq!([2, 3, 4], nice_slice) } diff --git a/exercises/primitive_types/primitive_types5.rs b/exercises/primitive_types/primitive_types5.rs index 680d8d23..9c9105eb 100644 --- a/exercises/primitive_types/primitive_types5.rs +++ b/exercises/primitive_types/primitive_types5.rs @@ -6,7 +6,7 @@ fn main() { let cat = ("Furry McFurson", 3.5); - let /* your pattern here */ = cat; + let (name, age) = cat; println!("{} is {} years old.", name, age); } diff --git a/exercises/primitive_types/primitive_types6.rs b/exercises/primitive_types/primitive_types6.rs index b8c9b82b..b0034372 100644 --- a/exercises/primitive_types/primitive_types6.rs +++ b/exercises/primitive_types/primitive_types6.rs @@ -9,7 +9,7 @@ fn indexing_tuple() { let numbers = (1, 2, 3); // Replace below ??? with the tuple indexing syntax. - let second = ???; + let second = numbers.1; assert_eq!(2, second, "This is not the 2nd number in the tuple!") diff --git a/exercises/quiz1.rs b/exercises/quiz1.rs index b13b9284..8822ed1a 100644 --- a/exercises/quiz1.rs +++ b/exercises/quiz1.rs @@ -12,6 +12,14 @@ // Put your function here! // fn calculate_apple_price { +fn calculate_apple_price(quantity: usize) -> usize { + if quantity <= 40 { + quantity * 2 + } else { + quantity * 1 + } +} + // Don't modify this function! #[test] fn verify_test() { diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index de0dce95..d6acee2d 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -17,14 +17,14 @@ fn string(arg: String) { } fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string_slice("blue"); + string("red".to_string()); + string(String::from("hi")); + string("rust is fun!".to_owned()); + string("nice weather".into()); + string(format!("Interpolation {}", "Station")); + string_slice(&String::from("abc")[0..1]); + string_slice(" hello there ".trim()); + string("Happy Monday!".to_string().replace("Mon", "Tues")); + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); } diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index fae0eedb..ada1ee65 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -19,12 +19,12 @@ mod tests { #[test] fn returns_twice_of_positive_numbers() { - assert_eq!(times_two(4), ???); + assert_eq!(times_two(4), 8); } #[test] fn returns_twice_of_negative_numbers() { // TODO replace unimplemented!() with an assert for `times_two(-4)` - unimplemented!() + assert_eq!(times_two(-4), -8); } } diff --git a/exercises/quiz4.rs b/exercises/quiz4.rs index 6c47480d..f67bf699 100644 --- a/exercises/quiz4.rs +++ b/exercises/quiz4.rs @@ -6,6 +6,11 @@ // Write a macro that passes the quiz! No hints this time, you can do it! // I AM NOT DONE +macro_rules! my_macro { + ($val:expr) => { + format!("Hello {}", $val) + }; +} #[cfg(test)] mod tests { diff --git a/exercises/standard_library_types/arc1.rs b/exercises/standard_library_types/arc1.rs index d167380c..21714330 100644 --- a/exercises/standard_library_types/arc1.rs +++ b/exercises/standard_library_types/arc1.rs @@ -23,17 +23,19 @@ #![forbid(unused_imports)] // Do not change this, (or the next) line. use std::sync::Arc; use std::thread; +use std::sync::Mutex; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(Mutex::new(numbers)); // TODO let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = Arc::clone(&shared_numbers); // TODO joinhandles.push(thread::spawn(move || { let mut i = offset; let mut sum = 0; + let child_numbers = child_numbers.lock().unwrap(); while i < child_numbers.len() { sum += child_numbers[i]; i += 8; diff --git a/exercises/standard_library_types/box1.rs b/exercises/standard_library_types/box1.rs index f312f3d6..32af08e1 100644 --- a/exercises/standard_library_types/box1.rs +++ b/exercises/standard_library_types/box1.rs @@ -20,7 +20,7 @@ #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } @@ -33,11 +33,11 @@ fn main() { } pub fn create_empty_list() -> List { - unimplemented!() + List::Nil } pub fn create_non_empty_list() -> List { - unimplemented!() + List::Cons(0, Box::new(List::Nil)) } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators1.rs b/exercises/standard_library_types/iterators1.rs index 4606ad35..1ec25132 100644 --- a/exercises/standard_library_types/iterators1.rs +++ b/exercises/standard_library_types/iterators1.rs @@ -13,12 +13,12 @@ fn main () { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2 assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2.1 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 2.1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 3 } diff --git a/exercises/standard_library_types/iterators2.rs b/exercises/standard_library_types/iterators2.rs index 87b4eaa1..a823eee7 100644 --- a/exercises/standard_library_types/iterators2.rs +++ b/exercises/standard_library_types/iterators2.rs @@ -12,7 +12,11 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => { + let mut s = first.to_string().to_uppercase(); + s.push_str(&input[1..]); + s + }, } } @@ -21,7 +25,11 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + let mut v = Vec::new(); + for word in words { + v.push(capitalize_first(word)); + } + v } // Step 3. @@ -29,7 +37,8 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + let v = capitalize_words_vector(words); + v.join("") } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators3.rs b/exercises/standard_library_types/iterators3.rs index 8c66c05b..8192c2c8 100644 --- a/exercises/standard_library_types/iterators3.rs +++ b/exercises/standard_library_types/iterators3.rs @@ -22,20 +22,34 @@ pub struct NotDivisibleError { // Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. -pub fn divide(a: i32, b: i32) -> Result {} +pub fn divide(a: i32, b: i32) -> Result { + if b == 0 { + Err(DivisionError::DivideByZero) + } else { + if a % b == 0 { + Ok(a / b) + } else { + Err(DivisionError::NotDivisible( + NotDivisibleError{dividend: a, divisor: b} + )) + } + } +} // Complete the function and return a value of the correct type so the test passes. // Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { +fn result_with_list() -> Result, DivisionError> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27).unwrap()).collect(); + Ok(division_results) } // Complete the function and return a value of the correct type so the test passes. // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect(); + division_results } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators4.rs b/exercises/standard_library_types/iterators4.rs index 88862838..6379bbe7 100644 --- a/exercises/standard_library_types/iterators4.rs +++ b/exercises/standard_library_types/iterators4.rs @@ -12,6 +12,11 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + let mut res = 1; + for i in 1..num+1 { + res *= i; + } + res } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators5.rs b/exercises/standard_library_types/iterators5.rs index 93f3ae11..6adb1b80 100644 --- a/exercises/standard_library_types/iterators5.rs +++ b/exercises/standard_library_types/iterators5.rs @@ -34,6 +34,13 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } + let mut count = 0; + for (_, val) in map.iter() { + if val == &value { + count += 1; + } + } + count } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -52,6 +59,15 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] + let mut count = 0; + for map in collection.iter() { + for (_, val) in map.iter() { + if val == &value { + count += 1; + } + } + } + count } #[cfg(test)] diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index 80902444..5df9ba25 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -10,5 +10,5 @@ fn main() { } fn current_favorite_color() -> String { - "blue" + "blue".to_string() } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 5a2ce74a..1d7c0395 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -6,7 +6,7 @@ fn main() { let word = String::from("green"); // Try not changing this line :) - if is_a_color_word(word) { + if is_a_color_word(&word[..]) { println!("That is a color word I know!"); } else { println!("That is not a color word I know."); diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs index 6d0b2f49..3a22eaae 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -3,11 +3,12 @@ // I AM NOT DONE -struct ColorClassicStruct { - // TODO: Something goes here +struct ColorClassicStruct<'a> { + name: &'a str, + hex: &'a str } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct<'a>(&'a str, &'a str); #[derive(Debug)] struct UnitStruct; @@ -19,7 +20,7 @@ mod tests { #[test] fn classic_c_structs() { // TODO: Instantiate a classic c struct! - // let green = + let green = ColorClassicStruct { name: "green", hex: "#00FF00" }; assert_eq!(green.name, "green"); assert_eq!(green.hex, "#00FF00"); @@ -28,7 +29,7 @@ mod tests { #[test] fn tuple_structs() { // TODO: Instantiate a tuple struct! - // let green = + let green = ColorTupleStruct ( "green", "#00FF00" ); assert_eq!(green.0, "green"); assert_eq!(green.1, "#00FF00"); @@ -36,8 +37,8 @@ mod tests { #[test] fn unit_structs() { - // TODO: Instantiate a unit struct! - // let unit_struct = + // TODO: Instantiate a unit struct + let unit_struct = UnitStruct; let message = format!("{:?}s are fun!", unit_struct); assert_eq!(message, "UnitStructs are fun!"); diff --git a/exercises/structs/structs2.rs b/exercises/structs/structs2.rs index f9c6427d..113e6152 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -34,7 +34,15 @@ mod tests { fn your_order() { let order_template = create_order_template(); // TODO: Create your own order using the update syntax and template above! - // let your_order = + let your_order = Order { + name: String::from("Hacker in Rust"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 1, + }; assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.year, order_template.year); assert_eq!(your_order.made_by_phone, order_template.made_by_phone); diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs index a80d0625..5e3c4854 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -17,6 +17,7 @@ impl Package { fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package { if weight_in_grams <= 0 { // Something goes here... + panic!("Weight of package is less than 0."); } else { return Package { sender_country, @@ -26,12 +27,12 @@ impl Package { } } - fn is_international(&self) -> ??? { - // Something goes here... + fn is_international(&self) -> bool { + self.sender_country != self.recipient_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { - // Something goes here... + fn get_fees(&self, cents_per_gram: i32) -> i32 { + self.weight_in_grams * cents_per_gram } } @@ -73,7 +74,7 @@ mod tests { let sender_country = String::from("Spain"); let recipient_country = String::from("Spain"); - let cents_per_gram = ???; + let cents_per_gram = 3; let package = Package::new(sender_country, recipient_country, 1500); diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 50586a19..7ba6363d 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -12,6 +12,6 @@ mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index 0d981ad1..2e19a0b5 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -8,6 +8,6 @@ mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1, 1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 3424f940..11c7dfd2 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -16,11 +16,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(2)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(!is_even(1)); } } diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index f31b317e..2ca1e453 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -9,6 +9,7 @@ // I AM NOT DONE use std::sync::Arc; +use std::sync::Mutex; use std::thread; use std::time::Duration; @@ -17,15 +18,15 @@ struct JobStatus { } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + let status = Arc::new(Mutex::new( JobStatus { jobs_completed: 0 })); let status_shared = status.clone(); thread::spawn(move || { for _ in 0..10 { thread::sleep(Duration::from_millis(250)); - status_shared.jobs_completed += 1; + status_shared.lock().unwrap().jobs_completed += 1; } }); - while status.jobs_completed < 10 { + while status.lock().unwrap().jobs_completed < 10 { println!("waiting... "); thread::sleep(Duration::from_millis(500)); } diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 2ef9e11b..b96e837a 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -16,6 +16,11 @@ trait AppendBar { impl AppendBar for String { //Add your code here + fn append_bar(self) -> Self { + let mut s = self.clone(); + s.push_str("Bar"); + s + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 916c3c4b..1864e726 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -17,6 +17,13 @@ trait AppendBar { } //TODO: Add your code here +impl AppendBar for Vec { + fn append_bar(self) -> Self { + let mut v = self.clone(); + v.push("Bar".to_string()); + return v; + } +} #[cfg(test)] mod tests { diff --git a/exercises/variables/variables1.rs b/exercises/variables/variables1.rs index 4a3af73c..8734065c 100644 --- a/exercises/variables/variables1.rs +++ b/exercises/variables/variables1.rs @@ -9,6 +9,6 @@ // I AM NOT DONE fn main() { - x = 5; + let x = 5; println!("x has the value {}", x); } diff --git a/exercises/variables/variables2.rs b/exercises/variables/variables2.rs index 7774a8fb..ced90b88 100644 --- a/exercises/variables/variables2.rs +++ b/exercises/variables/variables2.rs @@ -4,7 +4,7 @@ // I AM NOT DONE fn main() { - let x; + let x = 10; if x == 10 { println!("Ten!"); } else { diff --git a/exercises/variables/variables3.rs b/exercises/variables/variables3.rs index 30ec48ff..1f13bdad 100644 --- a/exercises/variables/variables3.rs +++ b/exercises/variables/variables3.rs @@ -4,7 +4,7 @@ // I AM NOT DONE fn main() { - let x = 3; + let mut x = 3; println!("Number {}", x); x = 5; // don't change this line println!("Number {}", x); diff --git a/exercises/variables/variables4.rs b/exercises/variables/variables4.rs index 77f1e9ab..b6e92741 100644 --- a/exercises/variables/variables4.rs +++ b/exercises/variables/variables4.rs @@ -4,6 +4,6 @@ // I AM NOT DONE fn main() { - let x: i32; + let x: i32 = 10; println!("Number {}", x); } diff --git a/exercises/variables/variables5.rs b/exercises/variables/variables5.rs index 175eebb3..cd9846aa 100644 --- a/exercises/variables/variables5.rs +++ b/exercises/variables/variables5.rs @@ -6,6 +6,6 @@ fn main() { let number = "T-H-R-E-E"; // don't change this line println!("Spell a Number : {}", number); - number = 3; + let number = 3; println!("Number plus two is : {}", number + 2); } diff --git a/exercises/variables/variables6.rs b/exercises/variables/variables6.rs index 98666914..6afe3542 100644 --- a/exercises/variables/variables6.rs +++ b/exercises/variables/variables6.rs @@ -3,7 +3,7 @@ // I AM NOT DONE -const NUMBER = 3; +const NUMBER: i8 = 3; fn main() { println!("Number {}", NUMBER); }