Skip to content

Commit

Permalink
Completed Error exercises.
Browse files Browse the repository at this point in the history
  • Loading branch information
Aziz Unsal authored and Aziz Unsal committed Nov 11, 2022
1 parent a1c9df0 commit d4d74d4
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 24 deletions.
9 changes: 5 additions & 4 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
// 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
use std::error::Error;
use std::result::Result;

pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
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))
}
}

Expand Down
8 changes: 6 additions & 2 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,19 @@
// 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<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();
/*match qty {
Ok(a) => Ok(a * cost_per_item + processing_fee),
Err(b) => Err(b)
}*/

// Shorter version
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}

Expand Down
16 changes: 8 additions & 8 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@
// 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() {
let mut tokens = 100;
let pretend_user_input = "8";

let cost = total_cost(pretend_user_input)?;
let cost = total_cost(pretend_user_input);

if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
if let Ok(c) = cost {
if c > tokens {
println!("You can't afford that many!");
} else {
tokens -= c;
println!("You now have {} tokens.", tokens);
}
}
}

Expand Down
8 changes: 6 additions & 2 deletions exercises/error_handling/errors4.rs
Original file line number Diff line number Diff line change
@@ -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);

Expand All @@ -15,6 +13,12 @@ enum CreationError {
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
if value.is_negative() {
return Err(CreationError::Negative);
}
if value == 0 {
return Err(CreationError::Zero);
}
Ok(PositiveNonzeroInteger(value as u64))
}
}
Expand Down
5 changes: 3 additions & 2 deletions exercises/error_handling/errors5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@

// 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<dyn ???>> {
fn main() -> Result<(), Box<dyn error::Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Expand Down Expand Up @@ -62,4 +61,6 @@ impl fmt::Display for CreationError {
}
}

// Why do we need to implement `Error`? See below link
// Dynamic error handling => https://nrc.github.io/error-docs/rust-errors/result-and-error.html#dynamic-error-handling
impl error::Error for CreationError {}
24 changes: 18 additions & 6 deletions exercises/error_handling/errors6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::num::ParseIntError;
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError)
ParseInt(ParseIntError),
}

impl ParsePosNonzeroError {
Expand All @@ -25,16 +25,28 @@ impl ParsePosNonzeroError {
}
// 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<PositiveNonzeroInteger, ParsePosNonzeroError>
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
// 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)
// when `parse()` returns an error.
let x: Result<i64, ParseIntError> = s.parse();
return match x {
Ok(num) => {
let crt = PositiveNonzeroInteger::new(num);
println!("Creation result. crt= {:?}", crt);
match crt {
Ok(ii) => Ok(ii),
Err(cr_err) => Err(ParsePosNonzeroError::from_creation(cr_err))
}
}
Err(err) => Err(ParsePosNonzeroError::from_parseint(err))
};
}

// Don't change anything below this line.
Expand Down

0 comments on commit d4d74d4

Please sign in to comment.