File tree Expand file tree Collapse file tree 3 files changed +46
-7
lines changed
Expand file tree Collapse file tree 3 files changed +46
-7
lines changed Original file line number Diff line number Diff line change @@ -40,10 +40,30 @@ impl Default for Person {
4040// If while parsing the age, something goes wrong, then return the default of
4141// Person Otherwise, then return an instantiated Person object with the results
4242
43- // I AM NOT DONE
44-
4543impl From < & str > for Person {
4644 fn from ( s : & str ) -> Person {
45+ if s. is_empty ( ) {
46+ return Person :: default ( ) ;
47+ }
48+
49+ let split: Vec < & str > = s. split ( "," ) . collect ( ) ;
50+ if split. len ( ) != 2 {
51+ return Person :: default ( ) ;
52+ }
53+
54+ let name = split[ 0 ] ;
55+
56+ if name. is_empty ( ) {
57+ return Person :: default ( ) ;
58+ }
59+
60+ match split[ 1 ] . parse :: < usize > ( ) {
61+ Ok ( age) => Person {
62+ name : name. to_string ( ) ,
63+ age : age,
64+ } ,
65+ Err ( _) => Person :: default ( ) ,
66+ }
4767 }
4868}
4969
Original file line number Diff line number Diff line change @@ -31,8 +31,6 @@ enum ParsePersonError {
3131 ParseInt ( ParseIntError ) ,
3232}
3333
34- // I AM NOT DONE
35-
3634// Steps:
3735// 1. If the length of the provided string is 0, an error should be returned
3836// 2. Split the given string on the commas present in it
@@ -52,6 +50,29 @@ enum ParsePersonError {
5250impl FromStr for Person {
5351 type Err = ParsePersonError ;
5452 fn from_str ( s : & str ) -> Result < Person , Self :: Err > {
53+ if s. is_empty ( ) {
54+ return Err ( ParsePersonError :: Empty ) ;
55+ }
56+
57+ let split: Vec < & str > = s. split ( "," ) . collect ( ) ;
58+
59+ if split. len ( ) != 2 {
60+ return Err ( ParsePersonError :: BadLen ) ;
61+ }
62+
63+ let name = split[ 0 ] ;
64+ if name. is_empty ( ) {
65+ return Err ( ParsePersonError :: NoName ) ;
66+ }
67+
68+ let age = split[ 1 ]
69+ . trim ( )
70+ . parse :: < usize > ( )
71+ . map_err ( ParsePersonError :: ParseInt ) ?;
72+ Ok ( Person {
73+ name : name. to_string ( ) ,
74+ age : age,
75+ } )
5576 }
5677}
5778
Original file line number Diff line number Diff line change 1010// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
1111// hint.
1212
13- // I AM NOT DONE
14-
1513fn average ( values : & [ f64 ] ) -> f64 {
1614 let total = values. iter ( ) . sum :: < f64 > ( ) ;
17- total / values. len ( )
15+ total / values. len ( ) as f64
1816}
1917
2018fn main ( ) {
You can’t perform that action at this time.
0 commit comments