summaryrefslogtreecommitdiff
path: root/exercises/error_handling/errors5.rs
diff options
context:
space:
mode:
authorTaylor Yu <tlyu@mit.edu>2021-06-06 23:05:01 -0500
committerTaylor Yu <tlyu@mit.edu>2021-06-06 23:08:57 -0500
commit68d3ac567cd5c23f5593c2f4df51612bca3d09a9 (patch)
tree75619fb6489e1cb7abbde7d35e29ba0b3ce055d2 /exercises/error_handling/errors5.rs
parent50ab289da6b9eb19a7486c341b00048c516b88c0 (diff)
feature: improve error_handling exercises
Add new exercises errors5 and errors6, to introduce boxed errors and custom error enums more gently. Delete errorsn, because it tried to do too much too soon.
Diffstat (limited to 'exercises/error_handling/errors5.rs')
-rw-r--r--exercises/error_handling/errors5.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs
new file mode 100644
index 0000000..1b11800
--- /dev/null
+++ b/exercises/error_handling/errors5.rs
@@ -0,0 +1,53 @@
+// errors5.rs
+
+// This program uses a completed version of the code from errors4.
+// It won't compile right now! Why?
+// Execute `rustlings hint errors5` for hints!
+
+// 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<(), ParseIntError> {
+ let pretend_user_input = "42";
+ let x: i64 = pretend_user_input.parse()?;
+ println!("output={:?}", PositiveNonzeroInteger::new(x)?);
+ Ok(())
+}
+
+// Don't change anything below this line.
+
+#[derive(PartialEq, Debug)]
+struct PositiveNonzeroInteger(u64);
+
+#[derive(PartialEq, Debug)]
+enum CreationError {
+ Negative,
+ Zero,
+}
+
+impl PositiveNonzeroInteger {
+ fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
+ match value {
+ x if x < 0 => Err(CreationError::Negative),
+ x if x == 0 => Err(CreationError::Zero),
+ x => Ok(PositiveNonzeroInteger(x as u64))
+ }
+ }
+}
+
+// This is required so that `CreationError` can implement `error::Error`.
+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 {}