complete: errors

This commit is contained in:
seth 2021-06-22 18:05:16 +08:00
parent 192725b336
commit 5ce4a201c9
4 changed files with 15 additions and 18 deletions

View file

@ -6,14 +6,12 @@
// this function to have.
// Execute `rustlings hint errors1` for hints!
// 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.len() > 0 {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".to_string())
}
}
@ -28,7 +26,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
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
// 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>();
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}

View file

@ -4,15 +4,13 @@
// 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() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
let cost = total_cost(pretend_user_input).unwrap();
if cost > tokens {
println!("You can't afford that many!");

View file

@ -17,19 +17,22 @@
//
// Execute `rustlings hint errorsn` for hints :)
// I AM NOT DONE
use std::error;
use std::fmt;
use std::io;
// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, ???> {
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, Box<dyn std::error::Error>> {
let mut line = String::new();
b.read_line(&mut line);
let num: i64 = line.trim().parse();
b.read_line(&mut line)?;
let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num);
answer
match answer {
Ok(answer) => Ok(answer),
Err(e) => {
Err(Box::new(e))
},
}
}
//