mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-05 10:19:18 +00:00
Add error conversion function and handle parse errors in parse_pos_nonzero
This commit is contained in:
parent
608ce4ffac
commit
3136192b9b
@ -10,6 +10,7 @@
|
|||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
// I AM NOT DONE
|
||||||
|
// NOTE: 重要
|
||||||
|
|
||||||
use std::num::ParseIntError;
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
@ -25,13 +26,26 @@ impl ParsePosNonzeroError {
|
|||||||
ParsePosNonzeroError::Creation(err)
|
ParsePosNonzeroError::Creation(err)
|
||||||
}
|
}
|
||||||
// TODO: add another error conversion function here.
|
// TODO: add another error conversion function here.
|
||||||
// fn from_parseint...
|
fn from_parseint(s: &str) -> Result<i64, ParsePosNonzeroError> {
|
||||||
|
match s.parse::<i64>() {
|
||||||
|
Ok(result) => {
|
||||||
|
if result == 0 {
|
||||||
|
Err(ParsePosNonzeroError::Creation(CreationError::Zero))
|
||||||
|
} else if result < 0 {
|
||||||
|
Err(ParsePosNonzeroError::Creation(CreationError::Negative))
|
||||||
|
} else {
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(err) => Err(ParsePosNonzeroError::ParseInt(err))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
|
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
|
||||||
// TODO: change this to return an appropriate error instead of panicking
|
// TODO: change this to return an appropriate error instead of panicking
|
||||||
// when `parse()` returns an error.
|
// when `parse()` returns an error.
|
||||||
let x: i64 = s.parse().unwrap();
|
let x: i64 = ParsePosNonzeroError::from_parseint(s)?;
|
||||||
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
|
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user