From 367c75fd1f4b8c80b855f4fdf76cb6aee515c9cf Mon Sep 17 00:00:00 2001 From: Jake Walker Date: Tue, 11 Oct 2022 18:32:19 +0100 Subject: [PATCH] Solutions 2 --- exercises/error_handling/errors1.rs | 8 +++----- exercises/error_handling/errors2.rs | 4 +--- exercises/error_handling/errors3.rs | 6 +++--- exercises/error_handling/errors4.rs | 10 +++++++--- exercises/error_handling/errors5.rs | 6 ++---- exercises/error_handling/errors6.rs | 12 +++++------- exercises/generics/generics1.rs | 4 +--- exercises/generics/generics2.rs | 10 ++++------ exercises/options/options1.rs | 12 ++++++++---- exercises/options/options2.rs | 6 ++---- exercises/options/options3.rs | 4 +--- exercises/quiz3.rs | 10 ++++------ exercises/traits/traits1.rs | 6 +++--- exercises/traits/traits2.rs | 9 ++++++--- exercises/traits/traits3.rs | 6 +++--- exercises/traits/traits4.rs | 4 +--- exercises/traits/traits5.rs | 4 +--- 17 files changed, 55 insertions(+), 66 deletions(-) diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index bcee972..6bfe94a 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -5,14 +5,12 @@ // construct to `Option` that can be used to express error conditions. Let's use it! // Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".into()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index 1cd8fc6..0bd0530 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -17,14 +17,12 @@ // one is a lot shorter! // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - 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::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index a2d2d19..438ec94 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -4,11 +4,9 @@ // Why not? What should we do to fix it? // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -20,6 +18,8 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + + return Ok(()) } pub fn total_cost(item_quantity: &str) -> Result { diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index 0efe8cc..4082e70 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -1,8 +1,6 @@ // errors4.rs // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -15,7 +13,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + if value > 0 { + Ok(PositiveNonzeroInteger(value as u64)) + } else if value == 0 { + Err(CreationError::Zero) + } else { + Err(CreationError::Negative) + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 2ba8f90..97c1359 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -7,7 +7,7 @@ // For now, think of the `Box` type as an "I want anything that does ???" type, which, given // Rust's usual standards for runtime safety, should strike you as somewhat lenient! -// In short, this particular use case for boxes is for when you want to own a value and you care only that it is a +// In short, this particular use case for boxes is for when you want to own a value and you care only that it is a // type which implements a particular trait. To do so, The Box is declared as of type Box where Trait is the trait // the compiler looks for on any value used in that context. For this exercise, that context is the potential errors // which can be returned in a Result. @@ -16,14 +16,12 @@ // Execute `rustlings hint errors5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::error; use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), Box> { +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 1306fb0..6c4ced2 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -8,8 +8,6 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; // This is a custom error type that we will be using in `parse_pos_nonzero()`. @@ -23,16 +21,16 @@ impl ParsePosNonzeroError { fn from_creation(err: CreationError) -> ParsePosNonzeroError { ParsePosNonzeroError::Creation(err) } - // TODO: add another error conversion function here. - // fn from_parseint... + + fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError { + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) -> Result { - // TODO: change this to return an appropriate error instead of panicking - // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); + let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?; PositiveNonzeroInteger::new(x) .map_err(ParsePosNonzeroError::from_creation) } diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 4c34ae4..e3ec91a 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -3,9 +3,7 @@ // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. -// 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 aedbd55..ef08444 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -3,14 +3,12 @@ // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint. -// 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/options/options1.rs b/exercises/options/options1.rs index d1735c2..088c300 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -1,8 +1,6 @@ // options1.rs // Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - // This function returns how much icecream there is left in the fridge. // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them // all, so there'll be no more left :( @@ -10,7 +8,13 @@ fn maybe_icecream(time_of_day: u16) -> Option { // We use the 24-hour system here, so 10PM is a value of 22 // The Option output should gracefully handle cases where time_of_day > 24. - ??? + if time_of_day < 22 { + Some(5) + } else if time_of_day <= 24 { + Some(0) + } else { + None + } } #[cfg(test)] @@ -29,7 +33,7 @@ mod tests { #[test] fn raw_value() { // TODO: Fix this test. How do you get at the value contained in the Option? - let icecreams = maybe_icecream(12); + let icecreams = maybe_icecream(12).unwrap(); assert_eq!(icecreams, 5); } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index b112047..1769e96 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -1,8 +1,6 @@ // options2.rs // Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { use super::*; @@ -13,7 +11,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -28,7 +26,7 @@ mod tests { // 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.pop() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, range); range -= 1; } diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 3f995c5..1dd0b37 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -1,8 +1,6 @@ // options3.rs // Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - struct Point { x: i32, y: i32, @@ -12,7 +10,7 @@ fn main() { let y: Option = Some(Point { x: 100, y: 200 }); match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.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/quiz3.rs b/exercises/quiz3.rs index 15dc469..6f6de57 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -14,15 +14,13 @@ // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// 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) @@ -50,7 +48,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/traits/traits1.rs b/exercises/traits/traits1.rs index 5b9d8d5..c9dcfa5 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -9,14 +9,14 @@ // implementing this trait. // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { - //Add your code here + fn append_bar(self) -> Self { + self + "Bar" + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 708bb19..bed1f8e 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -11,13 +11,16 @@ // you can do this! // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } -//TODO: Add your code here +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + self.push("Bar".to_string()); + self + } +} #[cfg(test)] mod tests { diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 6d2fd6c..7491a23 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -7,10 +7,10 @@ // Consider what you can add to the Licensed trait. // Execute `rustlings hint traits3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait Licensed { - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String { + "Some information".to_string() + } } struct SomeSoftware { diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 6b54166..ab2d644 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -4,8 +4,6 @@ // Don't change any line other than the marked one. // Execute `rustlings hint traits4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait Licensed { fn licensing_info(&self) -> String { "some information".to_string() @@ -20,7 +18,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { +fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index 0fbca28..b6378a1 100644 --- a/exercises/traits/traits5.rs +++ b/exercises/traits/traits5.rs @@ -4,8 +4,6 @@ // Don't change any line other than the marked one. // Execute `rustlings hint traits5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait SomeTrait { fn some_function(&self) -> bool { true @@ -27,7 +25,7 @@ impl SomeTrait for OtherStruct {} impl OtherTrait for OtherStruct {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { item.some_function() && item.other_function() }