mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-10 12:49:18 +00:00
conversions
This commit is contained in:
parent
0c72fc9936
commit
99e915d6da
@ -40,10 +40,36 @@ impl Default for Person {
|
|||||||
// If while parsing the age, something goes wrong, then return the default of
|
// If while parsing the age, something goes wrong, then return the default of
|
||||||
// Person Otherwise, then return an instantiated Person object with the results
|
// Person Otherwise, then return an instantiated Person object with the results
|
||||||
|
|
||||||
// I AM NOT DONE
|
// Requirements for the conversion:
|
||||||
|
// - string is not empty
|
||||||
|
// - I can split in 2 elements
|
||||||
|
// First element is a NOT empty string
|
||||||
|
// Second element is a string correctly representing a number
|
||||||
impl From<&str> for Person {
|
impl From<&str> for Person {
|
||||||
fn from(s: &str) -> Person {
|
fn from(s: &str) -> Person {
|
||||||
|
if s.len() == 0 {
|
||||||
|
Default::default()
|
||||||
|
} else {
|
||||||
|
let strs : Vec<&str> = s.split(',').collect();
|
||||||
|
if strs.len() == 2 {
|
||||||
|
let name = strs[0];
|
||||||
|
if name.len() > 0 {
|
||||||
|
let age = strs[1].parse::<usize>();
|
||||||
|
match age {
|
||||||
|
Ok(a) =>
|
||||||
|
Person {
|
||||||
|
name : name.to_string(),
|
||||||
|
age : a,
|
||||||
|
},
|
||||||
|
Err(_) => Default::default()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -10,11 +10,9 @@
|
|||||||
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
|
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
|
||||||
// hint.
|
// hint.
|
||||||
|
|
||||||
// I AM NOT DONE
|
|
||||||
|
|
||||||
fn average(values: &[f64]) -> f64 {
|
fn average(values: &[f64]) -> f64 {
|
||||||
let total = values.iter().sum::<f64>();
|
let total = values.iter().sum::<f64>();
|
||||||
total / values.len()
|
total / (values.len() as f64)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user