Completed exercise up to Traits
This commit is contained in:
@@ -3,7 +3,22 @@
|
||||
// someone eats it all, so no ice cream is left (value 0). Return `None` if
|
||||
// `hour_of_day` is higher than 23.
|
||||
fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
|
||||
// TODO: Complete the function body.
|
||||
if hour_of_day > 23 {
|
||||
None
|
||||
} else if hour_of_day < 22 {
|
||||
Some(5)
|
||||
} else {
|
||||
Some(0)
|
||||
}
|
||||
|
||||
// OR
|
||||
// fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
|
||||
// match hour_of_day {
|
||||
// 0..=21 => Some(5),
|
||||
// 22 | 23 => Some(0),
|
||||
// _ => None,
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -20,7 +35,7 @@ mod tests {
|
||||
// Option?
|
||||
let ice_creams = maybe_ice_cream(12);
|
||||
|
||||
assert_eq!(ice_creams, 5); // Don't change this line.
|
||||
assert_eq!(ice_creams, Some(5)); // Don't change this line.
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,7 +10,10 @@ mod tests {
|
||||
let optional_target = Some(target);
|
||||
|
||||
// TODO: Make this an if-let statement whose value is `Some`.
|
||||
word = optional_target {
|
||||
// word = optional_target {
|
||||
// assert_eq!(word, target);
|
||||
// }
|
||||
if let Some(word) = optional_target {
|
||||
assert_eq!(word, target);
|
||||
}
|
||||
}
|
||||
@@ -29,10 +32,16 @@ mod tests {
|
||||
// TODO: Make this a while-let statement. Remember that `Vec::pop()`
|
||||
// adds another layer of `Option`. You can do nested pattern matching
|
||||
// in if-let and while-let statements.
|
||||
integer = optional_integers.pop() {
|
||||
assert_eq!(integer, cursor);
|
||||
cursor -= 1;
|
||||
while let Some(integer) = optional_integers.pop() {
|
||||
if let Some(integer_value) = integer {
|
||||
println!("integer_value (left): {}, cursor (right): {}", integer_value, cursor);
|
||||
assert_eq!(integer_value, cursor);
|
||||
cursor -= 1;
|
||||
} else {
|
||||
println!("None value, cursor: {}", cursor);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
assert_eq!(cursor, 0);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ fn main() {
|
||||
|
||||
// TODO: Fix the compiler error by adding something to this match statement.
|
||||
match optional_point {
|
||||
Some(p) => println!("Coordinates are {},{}", p.x, p.y),
|
||||
Some(ref p) => println!("Coordinates are {},{}", p.x, p.y),
|
||||
_ => panic!("No match!"),
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
// construct to `Option` that can be used to express error conditions. Change
|
||||
// the function signature and body to return `Result<String, String>` instead
|
||||
// of `Option<String>`.
|
||||
fn generate_nametag_text(name: String) -> Option<String> {
|
||||
fn generate_nametag_text(name: String) -> Result<String, String> {
|
||||
if name.is_empty() {
|
||||
// Empty names aren't allowed
|
||||
None
|
||||
// None
|
||||
Err("Empty names aren't allowed".to_string())
|
||||
} else {
|
||||
Some(format!("Hi! My name is {name}"))
|
||||
// Some(format!("Hi! My name is {name}"))
|
||||
Ok(format!("Hi! My name is {name}"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,14 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
||||
let cost_per_item = 5;
|
||||
|
||||
// TODO: Handle the error case as described above.
|
||||
let qty = item_quantity.parse::<i32>();
|
||||
let qty = item_quantity.parse::<i32>()?;
|
||||
|
||||
// OR
|
||||
// let qty_result = item_quantity.parse::<i32>();
|
||||
// let qty = match qty_result {
|
||||
// Ok(number) => number,
|
||||
// Err(e) => return Err(e),
|
||||
// };
|
||||
|
||||
Ok(qty * cost_per_item + processing_fee)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
||||
|
||||
// TODO: Fix the compiler error by changing the signature and body of the
|
||||
// `main` function.
|
||||
fn main() {
|
||||
fn main() -> Result<(), ParseIntError>{
|
||||
let mut tokens = 100;
|
||||
let pretend_user_input = "8";
|
||||
|
||||
@@ -28,4 +28,6 @@ fn main() {
|
||||
tokens -= cost;
|
||||
println!("You now have {tokens} tokens.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -11,7 +11,13 @@ impl PositiveNonzeroInteger {
|
||||
fn new(value: i64) -> Result<Self, CreationError> {
|
||||
// TODO: This function shouldn't always return an `Ok`.
|
||||
// Read the tests below to clarify what should be returned.
|
||||
Ok(Self(value as u64))
|
||||
if value < 0 {
|
||||
Err(CreationError::Negative)
|
||||
} else if value == 0 {
|
||||
Err(CreationError::Zero)
|
||||
} else {
|
||||
Ok(Self(value as u64))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ impl PositiveNonzeroInteger {
|
||||
|
||||
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we
|
||||
// use to describe both errors? Is there a trait which both errors implement?
|
||||
fn main() {
|
||||
fn main() -> Result<(), Box<dyn Error>>{
|
||||
let pretend_user_input = "42";
|
||||
let x: i64 = pretend_user_input.parse()?;
|
||||
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
|
||||
|
||||
@@ -26,6 +26,9 @@ impl ParsePosNonzeroError {
|
||||
|
||||
// TODO: Add another error conversion function here.
|
||||
// fn from_parse_int(???) -> Self { ??? }
|
||||
fn from_parse_int(err: ParseIntError) -> Self {
|
||||
Self::ParseInt(err)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
@@ -43,7 +46,7 @@ impl PositiveNonzeroInteger {
|
||||
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
|
||||
// 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_parse_int)?;
|
||||
Self::new(x).map_err(ParsePosNonzeroError::from_creation)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ fn main() {
|
||||
// TODO: Fix the compiler error by annotating the type of the vector
|
||||
// `Vec<T>`. Choose `T` as some integer type that can be created from
|
||||
// `u8` and `i8`.
|
||||
let mut numbers = Vec::new();
|
||||
let mut numbers: Vec<i16> = Vec::new();
|
||||
|
||||
// Don't change the lines below.
|
||||
let n1: u8 = 42;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// This powerful wrapper provides the ability to store a positive integer value.
|
||||
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
|
||||
struct Wrapper {
|
||||
value: u32,
|
||||
struct Wrapper<T> {
|
||||
value: T,
|
||||
}
|
||||
|
||||
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
|
||||
impl Wrapper {
|
||||
fn new(value: u32) -> Self {
|
||||
impl<T> Wrapper<T> {
|
||||
fn new(value: T) -> Self {
|
||||
Wrapper { value }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,14 @@ trait AppendBar {
|
||||
|
||||
impl AppendBar for String {
|
||||
// TODO: Implement `AppendBar` for the type `String`.
|
||||
fn append_bar(self) -> Self{
|
||||
// In this i need to put mut in front of the parameter
|
||||
// self.push_str("Bar");
|
||||
// self
|
||||
|
||||
// This way is more readable
|
||||
self + "Bar"
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
@@ -4,6 +4,13 @@ trait AppendBar {
|
||||
|
||||
// TODO: Implement the trait `AppendBar` for a vector of strings.
|
||||
// `append_bar` should push the string "Bar" into the vector.
|
||||
impl AppendBar for Vec<String> {
|
||||
// TODO: Implement `AppendBar` for the type `String`.
|
||||
fn append_bar(mut self) -> Self{
|
||||
self.push("Bar".to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// You can optionally experiment here.
|
||||
|
||||
@@ -3,7 +3,9 @@ trait Licensed {
|
||||
// implementors like the two structs below can share that default behavior
|
||||
// without repeating the function.
|
||||
// The default license information should be the string "Default license".
|
||||
fn licensing_info(&self) -> String;
|
||||
fn licensing_info(&self) -> String {
|
||||
String::from("Default license")
|
||||
}
|
||||
}
|
||||
|
||||
struct SomeSoftware {
|
||||
|
||||
@@ -11,7 +11,8 @@ impl Licensed for SomeSoftware {}
|
||||
impl Licensed for OtherSoftware {}
|
||||
|
||||
// TODO: Fix the compiler error by only changing the signature of this function.
|
||||
fn compare_license_types(software1: ???, software2: ???) -> bool {
|
||||
fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool {
|
||||
// Impl Licensed means to accept every types that implement Licensed
|
||||
software1.licensing_info() == software2.licensing_info()
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ impl SomeTrait for OtherStruct {}
|
||||
impl OtherTrait for OtherStruct {}
|
||||
|
||||
// TODO: Fix the compiler error by only changing the signature of this function.
|
||||
fn some_func(item: ???) -> bool {
|
||||
fn some_func(item: impl SomeTrait + OtherTrait) -> bool {
|
||||
item.some_function() && item.other_function()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user