Hello,
A question about Rustlings!
So this exercise can be solved by returning a wrap-it-all Box<(dyn Error + 'static)> but I still have questions....
-
I understand that the trait Error was implemented for creation Error, so by pointing with dyn at Error, it encompasses the buffer error, the parsing error and the creation error. But why do we return dyn error + 'static in parenthesis** and why do we add a 'static flag to it? (yes, the compiler helped me a lot...) (I read the book chapter on errors and a gentle introduction to Rust on the same subject but it did not click).
** small edit here, just tested and the parenthesis are not necessary apparently! -
Also, I tried to make a new error type (SmileyErrors) and an encompassing enum category "StupidErrors".
I implemented the Error trait and tried and tried to implement the fmt::Display trait for Stupid error, but the compiler complains about:note: expected enum
std::result::Result<_, CreationError>
found enumstd::result::Result<PositiveNonzeroInteger, StupidErrors>
I obviously missed a big point about custom errors. How can I make this work?
Thank you for reading ![]()
use std::error;
use std::error::Error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
// PositiveNonzeroInteger is a struct defined below the tests.
fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, Box<(dyn Error + 'static)>> {
let mut line = String::new();
b.read_line(&mut line)?;
let num: i64 = line.trim().parse()?;
let answer = PositiveNonzeroInteger::new(num)?;
Ok(answer)
}
//
// Nothing below this needs to be modified
//
// This is a test helper function that turns a &str into a BufReader.
fn test_with_str(s: &str) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> {
let mut b = io::BufReader::new(s.as_bytes());
read_and_validate(&mut b)
}
#[test]
fn test_success() {
let x = test_with_str("42\n");
assert_eq!(PositiveNonzeroInteger(42), x.unwrap());
}
#[test]
fn test_not_num() {
let x = test_with_str("eleven billion\n");
assert!(x.is_err());
}
#[test]
fn test_non_positive() {
let x = test_with_str("-40\n");
assert!(x.is_err());
}
#[test]
fn test_bad_smiley() {
let smulan = test_with_str("😃");
assert!(smulan.is_err());
}
#[test]
fn test_ioerror() {
struct Broken;
impl io::Read for Broken {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "uh-oh!"))
}
}
let mut b = io::BufReader::new(Broken);
assert!(read_and_validate(&mut b).is_err());
assert_eq!("uh-oh!", read_and_validate(&mut b).unwrap_err().to_string());
}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, StupidErrors> {
if value == 0 {
Err(CreationError::Zero)
} else if value < 0 {
Err(CreationError::Negative)
} else if value == "😃" {
Err(SmileyError::Smiling)
} else if value == "😔" {
Err(SmileyError::Angry)
} else {
Ok(PositiveNonzeroInteger(value as u64))
}
}
}
#[derive(Debug)]
enum StupidErrors {
CreationError,
SmileyError,
}
impl error::Error for StupidErrors {}
impl fmt::Display for StupidErrors {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self)
}
}
#[test]
fn test_positive_nonzero_integer_creation() {
assert!(PositiveNonzeroInteger::new(10).is_ok());
assert_eq!(
Err(CreationError::Negative),
PositiveNonzeroInteger::new(-10)
);
assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
CreationError::Negative => "Number is negative",
CreationError::Zero => "Number is zero",
};
f.write_str(description)
}
}
impl error::Error for CreationError {}
#[derive(PartialEq, Debug)]
enum SmileyError {
Smiling,
Angry,
}
impl fmt::Display for SmileyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let information = match *self {
SmileyError::Smiling => "This is not a number: 😃 ",
SmileyError::Angry => "This is obviously not a number: 😔. I am disappointed.",
};
f.write_str(information)
}
}
impl error::Error for SmileyError {}