Update from_into exercise to use error handling instead of default values

- Replace From<&str> trait with TryFrom<&str> for proper error handling
- Add ParsePersonError enum with BadLen, NoName, and ParseInt variants
- Update all tests to expect appropriate errors instead of default Person values
- Maintain same error handling pattern as from_str exercise
- Add required imports for TryFrom and TryInto traits
This commit is contained in:
iaadi4 2025-10-02 21:06:06 +05:30
parent f80fbca12e
commit f7b50183f4

View File

@ -3,24 +3,27 @@
// You can read more about it in the documentation: // You can read more about it in the documentation:
// https://doc.rust-lang.org/std/convert/trait.From.html // https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)] use std::convert::{TryFrom, TryInto};
use std::num::ParseIntError;
#[derive(Debug, PartialEq)]
struct Person { struct Person {
name: String, name: String,
age: u8, age: u8,
} }
// We implement the Default trait to use it as a fallback when the provided // We will use this error type for the `TryFrom` implementation.
// string is not convertible into a `Person` object. #[derive(Debug, PartialEq)]
impl Default for Person { enum ParsePersonError {
fn default() -> Self { // Incorrect number of fields
Self { BadLen,
name: String::from("John"), // Empty name field
age: 30, NoName,
} // Wrapped error from parse::<u8>()
} ParseInt(ParseIntError),
} }
// TODO: Complete this `From` implementation to be able to parse a `Person` // TODO: Complete this `TryFrom` implementation to be able to parse a `Person`
// out of a string in the form of "Mark,20". // out of a string in the form of "Mark,20".
// Note that you'll need to parse the age component into a `u8` with something // Note that you'll need to parse the age component into a `u8` with something
// like `"4".parse::<u8>()`. // like `"4".parse::<u8>()`.
@ -28,103 +31,86 @@ impl Default for Person {
// Steps: // Steps:
// 1. Split the given string on the commas present in it. // 1. Split the given string on the commas present in it.
// 2. If the split operation returns less or more than 2 elements, return the // 2. If the split operation returns less or more than 2 elements, return the
// default of `Person`. // error `ParsePersonError::BadLen`.
// 3. Use the first element from the split operation as the name. // 3. Use the first element from the split operation as the name.
// 4. If the name is empty, return the default of `Person`. // 4. If the name is empty, return the error `ParsePersonError::NoName`.
// 5. Parse the second element from the split operation into a `u8` as the age. // 5. Parse the second element from the split operation into a `u8` as the age.
// 6. If parsing the age fails, return the default of `Person`. // 6. If parsing the age fails, return the error `ParsePersonError::ParseInt`.
impl From<&str> for Person { impl TryFrom<&str> for Person {
fn from(s: &str) -> Self {} type Error = ParsePersonError;
fn try_from(s: &str) -> Result<Self, Self::Error> {}
} }
fn main() { fn main() {
// Use the `from` function. // Use the `try_from` function.
let p1 = Person::from("Mark,20"); let p1 = Person::try_from("Mark,20");
println!("{p1:?}"); println!("{p1:?}");
// Since `From` is implemented for Person, we are able to use `Into`. // Since `TryFrom` is implemented for Person, we are able to use `try_into`.
let p2: Person = "Gerald,70".into(); let p2: Result<Person, ParsePersonError> = "Gerald,70".try_into();
println!("{p2:?}"); println!("{p2:?}");
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use ParsePersonError::*;
#[test] #[test]
fn test_default() { fn empty_input() {
let dp = Person::default(); assert_eq!(Person::try_from(""), Err(BadLen));
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
} }
#[test] #[test]
fn test_bad_convert() { fn good_input() {
let p = Person::from(""); let p = Person::try_from("John,32");
assert!(p.is_ok());
let p = p.unwrap();
assert_eq!(p.name, "John"); assert_eq!(p.name, "John");
assert_eq!(p.age, 30); assert_eq!(p.age, 32);
} }
#[test] #[test]
fn test_good_convert() { fn missing_age() {
let p = Person::from("Mark,20"); assert!(matches!(Person::try_from("John,"), Err(ParseInt(_))));
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
} }
#[test] #[test]
fn test_bad_age() { fn invalid_age() {
let p = Person::from("Mark,twenty"); assert!(matches!(Person::try_from("John,twenty"), Err(ParseInt(_))));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_missing_comma_and_age() { fn missing_comma_and_age() {
let p: Person = Person::from("Mark"); assert_eq!(Person::try_from("John"), Err(BadLen));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_missing_age() { fn missing_name() {
let p: Person = Person::from("Mark,"); assert_eq!(Person::try_from(",1"), Err(NoName));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_missing_name() { fn missing_name_and_age() {
let p: Person = Person::from(",1"); assert!(matches!(Person::try_from(","), Err(NoName | ParseInt(_))));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_missing_name_and_age() { fn missing_name_and_invalid_age() {
let p: Person = Person::from(","); assert!(matches!(
assert_eq!(p.name, "John"); Person::try_from(",one"),
assert_eq!(p.age, 30); Err(NoName | ParseInt(_)),
));
} }
#[test] #[test]
fn test_missing_name_and_invalid_age() { fn trailing_comma() {
let p: Person = Person::from(",one"); assert_eq!(Person::try_from("John,32,"), Err(BadLen));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_trailing_comma() { fn trailing_comma_and_some_string() {
let p: Person = Person::from("Mike,32,"); assert_eq!(Person::try_from("John,32,man"), Err(BadLen));
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_trailing_comma_and_some_string() {
let p: Person = Person::from("Mike,32,dog");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} }
} }