|
| 1 | +// The From trait is used for value-to-value conversions. |
| 2 | +// If From is implemented correctly for a type, the Into trait should work conversely. |
| 3 | +// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html |
| 4 | +#[derive(Debug)] |
| 5 | +struct Person { |
| 6 | + name: String, |
| 7 | + age: usize, |
| 8 | +} |
| 9 | + |
| 10 | +// We implement the Default trait to use it as a fallback |
| 11 | +// when the provided string is not convertible into a Person object |
| 12 | +impl Default for Person { |
| 13 | + fn default() -> Person { |
| 14 | + Person { |
| 15 | + name: String::from("John"), |
| 16 | + age: 30, |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +// I AM NOT DONE |
| 22 | +// Your task is to complete this implementation |
| 23 | +// in order for the line `let p = Person::from("Mark,20")` to compile |
| 24 | +// Please note that you'll need to parse the age component into a `usize` |
| 25 | +// with something like `"4".parse::<usize>()`. The outcome of this needs to |
| 26 | +// be handled appropriately. |
| 27 | +// |
| 28 | +// Steps: |
| 29 | +// 1. If the length of the provided string is 0, then return the default of Person |
| 30 | +// 2. Split the given string on the commas present in it |
| 31 | +// 3. Extract the first element from the split operation and use it as the name |
| 32 | +// 4. Extract the other element from the split operation and parse it into a `usize` as the age |
| 33 | +// If while parsing the age, something goes wrong, then return the default of Person |
| 34 | +// Otherwise, then return an instantiated Person onject with the results |
| 35 | +impl From<&str> for Person { |
| 36 | + fn from(s: &str) -> Person { |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +fn main() { |
| 41 | + // Use the `from` function |
| 42 | + let p1 = Person::from("Mark,20"); |
| 43 | + // Since From is implemented for Person, we should be able to use Into |
| 44 | + let p2: Person = "Gerald,70".into(); |
| 45 | + println!("{:?}", p1); |
| 46 | + println!("{:?}", p2); |
| 47 | +} |
| 48 | + |
| 49 | +#[cfg(test)] |
| 50 | +mod tests { |
| 51 | + use super::*; |
| 52 | + #[test] |
| 53 | + fn test_default() { |
| 54 | + // Test that the default person is 30 year old John |
| 55 | + let dp = Person::default(); |
| 56 | + assert_eq!(dp.name, "John"); |
| 57 | + assert_eq!(dp.age, 30); |
| 58 | + } |
| 59 | + #[test] |
| 60 | + fn test_bad_convert() { |
| 61 | + // Test that John is returned when bad string is provided |
| 62 | + let p = Person::from(""); |
| 63 | + assert_eq!(p.name, "John"); |
| 64 | + assert_eq!(p.age, 30); |
| 65 | + } |
| 66 | + #[test] |
| 67 | + fn test_good_convert() { |
| 68 | + // Test that "Mark,20" works |
| 69 | + let p = Person::from("Mark,20"); |
| 70 | + assert_eq!(p.name, "Mark"); |
| 71 | + assert_eq!(p.age, 20); |
| 72 | + } |
| 73 | +} |
0 commit comments