Skip to content

Commit

Permalink
error-options
Browse files Browse the repository at this point in the history
  • Loading branch information
guimo3 committed Nov 24, 2024
1 parent e6ff537 commit bb3776f
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 28 deletions.
7 changes: 3 additions & 4 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@
// 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<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
4 changes: 2 additions & 2 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@
// 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>();
let qty = item_quantity.parse::<i32>()?;

Ok(qty * cost_per_item + processing_fee)

}

#[cfg(test)]
Expand Down
5 changes: 3 additions & 2 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
// 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<(), Box<dyn std::error::Error>> {
let mut tokens = 100;
let pretend_user_input = "8";

Expand All @@ -23,6 +22,8 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}

Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
9 changes: 7 additions & 2 deletions exercises/error_handling/errors4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// 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 @@ -17,7 +16,13 @@ enum CreationError {
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
Ok(PositiveNonzeroInteger(value as u64))
if value == 0 {
Err(CreationError::Zero)
} else if value < 0 {
Err(CreationError::Negative)
} else {
Ok(PositiveNonzeroInteger(value as u64))
}
}
}

Expand Down
3 changes: 1 addition & 2 deletions exercises/error_handling/errors5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,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 std::error::Error>> {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Expand Down
6 changes: 4 additions & 2 deletions exercises/error_handling/errors6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::num::ParseIntError;

Expand All @@ -26,12 +25,15 @@ 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> {
// 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)
}

Expand Down
11 changes: 8 additions & 3 deletions exercises/options/options1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// 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
Expand All @@ -13,7 +12,13 @@ fn maybe_icecream(time_of_day: u16) -> Option<u16> {
// value of 0 The Option output should gracefully handle cases where
// time_of_day > 23.
// TODO: Complete the function body - remember to return an Option!
???
if time_of_day == 22 || time_of_day == 23 {
Some(0)
} else if time_of_day <= 22 {
Some(5)
} else {
None
}
}

#[cfg(test)]
Expand All @@ -34,6 +39,6 @@ mod tests {
// TODO: Fix this test. How do you get at the value contained in the
// Option?
let icecreams = maybe_icecream(12);
assert_eq!(icecreams, 5);
assert_eq!(icecreams, Some(5));
}
}
11 changes: 6 additions & 5 deletions exercises/options/options2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint options2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[cfg(test)]
mod tests {
Expand All @@ -13,7 +12,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);
}
}
Expand All @@ -32,9 +31,11 @@ mod tests {
// TODO: make this a while let statement - remember that vector.pop also
// adds another layer of Option<T>. You can stack `Option<T>`s into
// while let and if let.
integer = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
while let Some(integer) = optional_integers.pop() {
if let Some(value) = integer {
assert_eq!(value, cursor);
cursor -= 1;
}
}

assert_eq!(cursor, 0);
Expand Down
3 changes: 1 addition & 2 deletions exercises/options/options3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint options3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

struct Point {
x: i32,
Expand All @@ -14,7 +13,7 @@ fn main() {
let y: Option<Point> = 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),
_ => panic!("no match!"),
}
y; // Fix without deleting this line.
Expand Down
15 changes: 11 additions & 4 deletions exercises/quiz2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
//
// No hints this time!

// I AM NOT DONE

pub enum Command {
Uppercase,
Expand All @@ -32,11 +31,19 @@ mod my_module {
use super::Command;

// TODO: Complete the function signature!
pub fn transformer(input: ???) -> ??? {
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
// TODO: Complete the output declaration!
let mut output: ??? = vec![];
let mut output: Vec<String> = vec![];
for (string, command) in input.iter() {
// TODO: Complete the function body. You can do it!
let transformed = match command {
Command::Uppercase => string.to_uppercase(),
Command::Trim => string.trim().to_string(),
Command::Append(count) => {
format!("{}{}", string, "bar".repeat(*count))
},
};
output.push(transformed);
}
output
}
Expand All @@ -45,7 +52,7 @@ mod my_module {
#[cfg(test)]
mod tests {
// TODO: What do we need to import to have `transformer` in scope?
use ???;
use crate::my_module::transformer;
use super::Command;

#[test]
Expand Down

0 comments on commit bb3776f

Please sign in to comment.