mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-09 20:29:18 +00:00
error handling
This commit is contained in:
parent
f458a97e00
commit
5fc192bf5c
@ -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>();
|
||||
match qty {
|
||||
Ok(qty) => Ok(qty * cost_per_item + processing_fee),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
|
||||
Ok(qty * cost_per_item + processing_fee)
|
||||
//Ok(qty * cost_per_item + processing_fee)
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@ -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> {
|
||||
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user