error handling

This commit is contained in:
Surya 2021-07-09 15:01:26 +05:30
parent f458a97e00
commit 5fc192bf5c
3 changed files with 15 additions and 9 deletions

View File

@ -16,18 +16,21 @@
// 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.
// 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>();
Ok(qty * cost_per_item + processing_fee)
match qty {
Ok(qty) => Ok(qty * cost_per_item + processing_fee),
Err(e) => Err(e),
}
//Ok(qty * cost_per_item + processing_fee)
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -4,11 +4,9 @@
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn main() {
fn main() -> Result<(), ParseIntError>{
let mut tokens = 100;
let pretend_user_input = "8";
@ -20,6 +18,7 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
Ok(())
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {

View File

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