from_into solution

This commit is contained in:
mo8it 2024-07-01 22:09:48 +02:00
parent 428d64ffa0
commit cddaf4881e
3 changed files with 167 additions and 34 deletions

View file

@ -1,81 +1,79 @@
// The From trait is used for value-to-value conversions. If From is implemented // The `From` trait is used for value-to-value conversions. If `From` is
// correctly for a type, the Into trait should work conversely. You can read // implemented, an implementation of `Into` is automatically provided.
// more about it at https://doc.rust-lang.org/std/convert/trait.From.html // You can read more about it in the documentation:
// https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)] #[derive(Debug)]
struct Person { struct Person {
name: String, name: String,
age: usize, age: u8,
} }
// We implement the Default trait to use it as a fallback // We implement the Default trait to use it as a fallback when the provided
// when the provided string is not convertible into a Person object // string is not convertible into a `Person` object.
impl Default for Person { impl Default for Person {
fn default() -> Person { fn default() -> Self {
Person { Self {
name: String::from("John"), name: String::from("John"),
age: 30, age: 30,
} }
} }
} }
// Your task is to complete this implementation in order for the line `let p1 = // TODO: Complete this `From` implementation to be able to parse a `Person`
// Person::from("Mark,20")` to compile. Please note that you'll need to parse the // out of a string in the form of "Mark,20".
// age component into a `usize` with something like `"4".parse::<usize>()`. The // Note that you'll need to parse the age component into a `u8` with something
// outcome of this needs to be handled appropriately. // like `"4".parse::<u8>()`.
// //
// Steps: // Steps:
// 1. If the length of the provided string is 0, then return the default of // 1. Split the given string on the commas present in it.
// Person. // 2. If the split operation returns less or more than 2 elements, return the
// 2. Split the given string on the commas present in it. // default of `Person`.
// 3. Extract the first element from the split operation and use it as the name. // 3. Use the first element from the split operation as the name.
// 4. If the name is empty, then return the default of Person. // 4. If the name is empty, return the default of `Person`.
// 5. Extract the other element from the split operation and parse it into a // 5. Parse the second element from the split operation into a `u8` as the age.
// `usize` as the age. // 6. If parsing the age fails, return the default of `Person`.
// If while parsing the age, something goes wrong, then return the default of
// Person. Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person { impl From<&str> for Person {
fn from(s: &str) -> Person {} fn from(s: &str) -> Self {}
} }
fn main() { fn main() {
// Use the `from` function // Use the `from` function.
let p1 = Person::from("Mark,20"); let p1 = Person::from("Mark,20");
// Since From is implemented for Person, we should be able to use Into println!("{p1:?}");
// Since `From` is implemented for Person, we are able to use `Into`.
let p2: Person = "Gerald,70".into(); let p2: Person = "Gerald,70".into();
println!("{:?}", p1); println!("{p2:?}");
println!("{:?}", p2);
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_default() { fn test_default() {
// Test that the default person is 30 year old John
let dp = Person::default(); let dp = Person::default();
assert_eq!(dp.name, "John"); assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30); assert_eq!(dp.age, 30);
} }
#[test] #[test]
fn test_bad_convert() { fn test_bad_convert() {
// Test that John is returned when bad string is provided
let p = Person::from(""); let p = Person::from("");
assert_eq!(p.name, "John"); assert_eq!(p.name, "John");
assert_eq!(p.age, 30); assert_eq!(p.age, 30);
} }
#[test] #[test]
fn test_good_convert() { fn test_good_convert() {
// Test that "Mark,20" works
let p = Person::from("Mark,20"); let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark"); assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20); assert_eq!(p.age, 20);
} }
#[test] #[test]
fn test_bad_age() { fn test_bad_age() {
// Test that "Mark,twenty" will return the default person due to an
// error in parsing age
let p = Person::from("Mark,twenty"); let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John"); assert_eq!(p.name, "John");
assert_eq!(p.age, 30); assert_eq!(p.age, 30);

View file

@ -1174,7 +1174,7 @@ Use the `as` operator to cast one of the operands in the last line of the
name = "from_into" name = "from_into"
dir = "23_conversions" dir = "23_conversions"
hint = """ hint = """
Follow the steps provided right before the `From` implementation""" Follow the steps provided right before the `From` implementation."""
[[exercises]] [[exercises]]
name = "from_str" name = "from_str"

View file

@ -1 +1,136 @@
// Solutions will be available before the stable release. Thank you for testing the beta version 🥰 // The `From` trait is used for value-to-value conversions. If `From` is
// implemented, an implementation of `Into` is automatically provided.
// You can read more about it in the documentation:
// https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// We implement the Default trait to use it as a fallback when the provided
// string is not convertible into a `Person` object.
impl Default for Person {
fn default() -> Self {
Self {
name: String::from("John"),
age: 30,
}
}
}
impl From<&str> for Person {
fn from(s: &str) -> Self {
let mut split = s.split(',');
let (Some(name), Some(age), None) = (split.next(), split.next(), split.next()) else {
// ^^^^ there should be no third element
return Self::default();
};
if name.is_empty() {
return Self::default();
}
let Ok(age) = age.parse() else {
return Self::default();
};
Self {
name: name.into(),
age,
}
}
}
fn main() {
// Use the `from` function.
let p1 = Person::from("Mark,20");
println!("{p1:?}");
// Since `From` is implemented for Person, we are able to use `Into`.
let p2: Person = "Gerald,70".into();
println!("{p2:?}");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let dp = Person::default();
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
let p = Person::from("");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_comma_and_age() {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_invalid_age() {
let p: Person = Person::from(",one");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_trailing_comma() {
let p: Person = Person::from("Mike,32,");
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);
}
}