Solve threads and some conversions

This commit is contained in:
Enrico Bozzolini 2020-09-11 22:26:26 +02:00
parent 8039ced662
commit 5b073bb05d
3 changed files with 27 additions and 9 deletions

View File

@ -18,7 +18,6 @@ impl Default for Person {
}
}
// I AM NOT DONE
// Your task is to complete this implementation
// in order for the line `let p = Person::from("Mark,20")` to compile
// Please note that you'll need to parse the age component into a `usize`
@ -35,6 +34,23 @@ impl Default for Person {
// Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person {
fn from(s: &str) -> Person {
// Can be neglected as in this case the age rule will always fail
// if s.len() == 0 {
// return Person::default();
// }
let mut splits = s.splitn(2, ',');
let name = splits.next().unwrap();
let part = splits.next().unwrap_or_default().parse::<usize>();
// Person can never be aged 0
let age = part.unwrap_or_default();
if name.len() > 0 && age > 0 {
return Person {
name: String::from(name),
age: age
}
} else {
return Person::default();
}
}
}
@ -75,6 +91,7 @@ mod tests {
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");
println!("{:?}", p);
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}

View File

@ -2,13 +2,12 @@
// Please note that the `as` operator is not only used when type casting.
// It also helps with renaming imports.
// I AM NOT DONE
// The goal is to make sure that the division does not fail to compile
fn average(values: &[f64]) -> f64 {
let total = values
.iter()
.fold(0.0, |a, b| a + b);
total / values.len()
total / (values.len() as f64)
}
fn main() {

View File

@ -5,9 +5,7 @@
// of "waiting..." and the program ends without timing out when running,
// you've got it :)
// I AM NOT DONE
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
@ -16,15 +14,19 @@ struct JobStatus {
}
fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
// Introduce Mutex
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone();
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
status_shared.jobs_completed += 1;
// Lock mutex and make mutable
let mut jobStatus = status_shared.lock().unwrap();
jobStatus.jobs_completed += 1;
}
});
while status.jobs_completed < 10 {
// Not assigning should release lock before sleep
while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... ");
thread::sleep(Duration::from_millis(500));
}