Solve error handling exercises.

This commit is contained in:
Leonardo Freua 2021-09-14 10:20:06 -03:00
parent fc9fddce0e
commit 1412f25125
6 changed files with 18 additions and 25 deletions

View File

@ -6,14 +6,10 @@
// this function to have. // this function to have.
// Execute `rustlings hint errors1` for hints! // Execute `rustlings hint errors1` for hints!
// I AM NOT DONE pub fn generate_nametag_text(name: String) -> Result<String, String> {
match name.len() > 0 {
pub fn generate_nametag_text(name: String) -> Option<String> { true => Ok(format!("Hi! My name is {}", name)),
if name.len() > 0 { _ => Err("`name` was empty; it must be nonempty.".into()),
Some(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
} }
} }
@ -28,7 +24,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() { fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!( assert_eq!(
generate_nametag_text("Beyoncé".into()), generate_nametag_text("Beyoncé".into()),
Some("Hi! My name is Beyoncé".into()) Ok("Hi! My name is Beyoncé".into())
); );
} }

View File

@ -16,14 +16,12 @@
// There are at least two ways to implement this that are both correct-- but // There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways. // one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1; let processing_fee = 1;
let cost_per_item = 5; let cost_per_item = 5;
let qty = item_quantity.parse::<i32>(); let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee) Ok(qty * cost_per_item + processing_fee)
} }

View File

@ -4,15 +4,13 @@
// Why not? What should we do to fix it? // Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints! // Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
fn main() { 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

@ -1,8 +1,6 @@
// errors4.rs // errors4.rs
// Make this test pass! Execute `rustlings hint errors4` for hints :) // Make this test pass! Execute `rustlings hint errors4` for hints :)
// I AM NOT DONE
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64); struct PositiveNonzeroInteger(u64);
@ -14,6 +12,11 @@ enum CreationError {
impl PositiveNonzeroInteger { impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> { fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
if value == 0 {
return Err(CreationError::Zero);
} else if value < 0 {
return Err(CreationError::Negative);
}
Ok(PositiveNonzeroInteger(value as u64)) Ok(PositiveNonzeroInteger(value as u64))
} }
} }

View File

@ -4,14 +4,12 @@
// It won't compile right now! Why? // It won't compile right now! Why?
// Execute `rustlings hint errors5` for hints! // Execute `rustlings hint errors5` for hints!
// I AM NOT DONE
use std::error; use std::error;
use std::fmt; use std::fmt;
use std::num::ParseIntError; use std::num::ParseIntError;
// TODO: update the return type of `main()` to make this compile. // TODO: update the return type of `main()` to make this compile.
fn main() -> Result<(), ParseIntError> { fn main() -> Result<(), Box<dyn error::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

@ -8,8 +8,6 @@
// Make these tests pass! Execute `rustlings hint errors6` for hints :) // Make these tests pass! Execute `rustlings hint errors6` for hints :)
// I AM NOT DONE
use std::num::ParseIntError; use std::num::ParseIntError;
// This is a custom error type that we will be using in `parse_pos_nonzero()`. // This is a custom error type that we will be using in `parse_pos_nonzero()`.
@ -24,14 +22,16 @@ impl ParsePosNonzeroError {
ParsePosNonzeroError::Creation(err) ParsePosNonzeroError::Creation(err)
} }
// TODO: add another error conversion function here. // TODO: add another error conversion function here.
fn from_parse_int(err: ParseIntError) -> ParsePosNonzeroError {
ParsePosNonzeroError::ParseInt(err)
}
} }
fn parse_pos_nonzero(s: &str) fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError> -> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{ {
// TODO: change this to return an appropriate error instead of panicking let x = s.parse()
// when `parse()` returns an error. .map_err(ParsePosNonzeroError::from_parse_int)?;
let x: i64 = s.parse().unwrap();
PositiveNonzeroInteger::new(x) PositiveNonzeroInteger::new(x)
.map_err(ParsePosNonzeroError::from_creation) .map_err(ParsePosNonzeroError::from_creation)
} }