coding 12、13

This commit is contained in:
jiangker 2024-07-11 14:48:30 +08:00
parent deadba31d5
commit e5630438f2
9 changed files with 25 additions and 16 deletions

View File

@ -3,7 +3,9 @@
// someone eats it all, so no icecream is left (value 0). Return `None` if // someone eats it all, so no icecream is left (value 0). Return `None` if
// `hour_of_day` is higher than 23. // `hour_of_day` is higher than 23.
fn maybe_icecream(hour_of_day: u16) -> Option<u16> { fn maybe_icecream(hour_of_day: u16) -> Option<u16> {
// TODO: Complete the function body. if hour_of_day < 22 { Some(5) }
else if hour_of_day < 24 { Some(0) }
else { None }
} }
fn main() { fn main() {
@ -18,7 +20,7 @@ mod tests {
fn raw_value() { fn raw_value() {
// TODO: Fix this test. How do you get the value contained in the // TODO: Fix this test. How do you get the value contained in the
// Option? // Option?
let icecreams = maybe_icecream(12); let icecreams = maybe_icecream(12).unwrap();
assert_eq!(icecreams, 5); // Don't change this line. assert_eq!(icecreams, 5); // Don't change this line.
} }

View File

@ -10,7 +10,7 @@ mod tests {
let optional_target = Some(target); let optional_target = Some(target);
// TODO: Make this an if-let statement whose value is `Some`. // TODO: Make this an if-let statement whose value is `Some`.
word = optional_target { if let Some(word) = optional_target {
assert_eq!(word, target); assert_eq!(word, target);
} }
} }
@ -29,7 +29,7 @@ mod tests {
// TODO: Make this a while-let statement. Remember that `Vec::pop()` // TODO: Make this a while-let statement. Remember that `Vec::pop()`
// adds another layer of `Option`. You can do nested pattern matching // adds another layer of `Option`. You can do nested pattern matching
// in if-let and while-let statements. // in if-let and while-let statements.
integer = optional_integers.pop() { while let Some(Some(integer)) = optional_integers.pop() {
assert_eq!(integer, cursor); assert_eq!(integer, cursor);
cursor -= 1; cursor -= 1;
} }

View File

@ -9,7 +9,7 @@ fn main() {
// TODO: Fix the compiler error by adding something to this match statement. // TODO: Fix the compiler error by adding something to this match statement.
match optional_point { match optional_point {
Some(p) => println!("Co-ordinates are {},{}", p.x, p.y), Some(ref p) => println!("Co-ordinates are {},{}", p.x, p.y),
_ => panic!("No match!"), _ => panic!("No match!"),
} }

View File

@ -4,12 +4,12 @@
// construct to `Option` that can be used to express error conditions. Change // construct to `Option` that can be used to express error conditions. Change
// the function signature and body to return `Result<String, String>` instead // the function signature and body to return `Result<String, String>` instead
// of `Option<String>`. // of `Option<String>`.
fn generate_nametag_text(name: String) -> Option<String> { fn generate_nametag_text(name: String) -> Result<String, String> {
if name.is_empty() { if name.is_empty() {
// Empty names aren't allowed. // Empty names aren't allowed.
None Err("Empty names aren't allowed".to_string())
} else { } else {
Some(format!("Hi! My name is {name}")) Ok(format!("Hi! My name is {name}"))
} }
} }

View File

@ -22,8 +22,10 @@ fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
// TODO: Handle the error case as described above. // TODO: Handle the error case as described above.
let qty = item_quantity.parse::<i32>(); let qty = item_quantity.parse::<i32>();
match qty {
Ok(qty * cost_per_item + processing_fee) Ok(v) => { Ok(v * cost_per_item + processing_fee) }
Err(e) => { Err(e) }
}
} }
fn main() { fn main() {

View File

@ -19,7 +19,7 @@ fn main() {
let mut tokens = 100; let mut tokens = 100;
let pretend_user_input = "8"; let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?; let cost = total_cost(pretend_user_input).unwrap();
if cost > tokens { if cost > tokens {
println!("You can't afford that many!"); println!("You can't afford that many!");

View File

@ -11,8 +11,13 @@ struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger { impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<Self, CreationError> { fn new(value: i64) -> Result<Self, CreationError> {
// TODO: This function shouldn't always return an `Ok`. if value > 0 {
Ok(Self(value as u64)) Ok(Self(value as u64))
} else if value == 0 {
Err(CreationError::Zero)
} else {
Err(CreationError::Negative)
}
} }
} }

View File

@ -48,7 +48,7 @@ impl PositiveNonzeroInteger {
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we // 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? // 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 pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?; let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?); println!("output={:?}", PositiveNonzeroInteger::new(x)?);

View File

@ -25,7 +25,7 @@ impl ParsePosNonzeroError {
} }
// TODO: Add another error conversion function here. // TODO: Add another error conversion function here.
// fn from_parseint(???) -> Self { ??? } fn from_parseint(err: ParseIntError) -> Self { Self::ParseInt(err) }
} }
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
@ -43,7 +43,7 @@ impl PositiveNonzeroInteger {
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> { fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
// TODO: change this to return an appropriate error instead of panicking // TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error. // when `parse()` returns an error.
let x: i64 = s.parse().unwrap(); let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?;
Self::new(x).map_err(ParsePosNonzeroError::from_creation) Self::new(x).map_err(ParsePosNonzeroError::from_creation)
} }
} }