mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-11 13:19:18 +00:00
finished
This commit is contained in:
parent
a6c8169de1
commit
5f724516da
@ -16,8 +16,6 @@
|
||||
// 4. Complete the partial implementation of `Display` for
|
||||
// `ParseClimateError`.
|
||||
|
||||
// I AM NOT DONE
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::num::{ParseFloatError, ParseIntError};
|
||||
@ -38,7 +36,7 @@ enum ParseClimateError {
|
||||
// `ParseIntError` values.
|
||||
impl From<ParseIntError> for ParseClimateError {
|
||||
fn from(e: ParseIntError) -> Self {
|
||||
Self::ParseInt(e)
|
||||
ParseClimateError::ParseInt(e)
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,12 +44,15 @@ impl From<ParseIntError> for ParseClimateError {
|
||||
// `ParseFloatError` values.
|
||||
impl From<ParseFloatError> for ParseClimateError {
|
||||
fn from(e: ParseFloatError) -> Self {
|
||||
// TODO: Complete this function
|
||||
ParseClimateError::ParseFloat(e)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Implement a missing trait so that `main()` below will compile. It
|
||||
// is not necessary to implement any methods inside the missing trait.
|
||||
impl Error for ParseClimateError {
|
||||
|
||||
}
|
||||
|
||||
// The `Display` trait allows for other code to obtain the error formatted
|
||||
// as a user-visible string.
|
||||
@ -64,6 +65,9 @@ impl Display for ParseClimateError {
|
||||
match self {
|
||||
NoCity => write!(f, "no city name"),
|
||||
ParseFloat(e) => write!(f, "error parsing temperature: {}", e),
|
||||
Empty => write!(f, "empty input"),
|
||||
BadLen => write!(f, "incorrect number of fields"),
|
||||
ParseInt(e) => write!(f, "error parsing year: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -88,13 +92,23 @@ impl FromStr for Climate {
|
||||
// TODO: Complete this function by making it handle the missing error
|
||||
// cases.
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
if s.len() == 0 {
|
||||
return Err(ParseClimateError::Empty);
|
||||
}
|
||||
let v: Vec<_> = s.split(',').collect();
|
||||
let (city, year, temp) = match &v[..] {
|
||||
[city, _, _] if city.len() == 0 => return Err(ParseClimateError::NoCity),
|
||||
[city, year, temp] => (city.to_string(), year, temp),
|
||||
_ => return Err(ParseClimateError::BadLen),
|
||||
};
|
||||
let year: u32 = year.parse()?;
|
||||
let temp: f32 = temp.parse()?;
|
||||
let year: u32 = match year.parse() {
|
||||
Ok(year) => year,
|
||||
Err(err) => return Err(ParseClimateError::ParseInt(err)),
|
||||
};
|
||||
let temp: f32 = match temp.parse() {
|
||||
Ok(temp) => temp,
|
||||
Err(err) => return Err(ParseClimateError::ParseFloat(err)),
|
||||
};
|
||||
Ok(Climate { city, year, temp })
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user