From b9df5b16f20e3a80ef248f7943c48712525a64a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=8A=20=E6=B1=9F?= Date: Tue, 10 Oct 2023 07:22:27 +0000 Subject: [PATCH] 20231010 --- exercises/clippy/clippy1.rs | 4 +-- exercises/clippy/clippy2.rs | 7 ++++-- exercises/clippy/clippy3.rs | 13 +++++----- exercises/conversions/as_ref_mut.rs | 10 ++++---- exercises/conversions/from_into.rs | 18 ++++++++++++- exercises/conversions/from_str.rs | 22 +++++++++++++++- exercises/conversions/try_from_into.rs | 35 +++++++++++++++++++++++++- exercises/conversions/using_as.rs | 4 +-- exercises/iterators/iterators1.rs | 10 ++++---- exercises/iterators/iterators2.rs | 22 +++++++++++++--- exercises/iterators/iterators3.rs | 22 +++++++++++----- exercises/iterators/iterators4.rs | 7 +++++- exercises/iterators/iterators5.rs | 8 +++--- exercises/macros/macros1.rs | 4 +-- exercises/macros/macros2.rs | 3 ++- exercises/macros/macros3.rs | 3 ++- exercises/macros/macros4.rs | 8 +++--- exercises/smart_pointers/arc1.rs | 6 ++--- exercises/smart_pointers/box1.rs | 10 +++++--- exercises/smart_pointers/cow1.rs | 11 +++++--- exercises/smart_pointers/rc1.rs | 11 +++++--- exercises/threads/threads1.rs | 3 ++- exercises/threads/threads2.rs | 11 ++++---- exercises/threads/threads3.rs | 6 +++-- 24 files changed, 188 insertions(+), 70 deletions(-) diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index 95c0141f..3b01ad5c 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -9,12 +9,12 @@ // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::f32; fn main() { - let pi = 3.14f32; + let pi = f32::consts::PI; let radius = 5.00f32; let area = pi * f32::powi(radius, 2); diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index 9b87a0b7..d01e173f 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -3,12 +3,15 @@ // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn main() { let mut res = 42; let option = Some(12); - for x in option { + /*for x in option { + res += x; + }*/ + if let Some(x) = option { res += x; } println!("{}", res); diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index 5a95f5b8..b577532c 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -3,28 +3,29 @@ // Here's a couple more easy Clippy fixes, so you can see its utility. // No hints. -// I AM NOT DONE + #[allow(unused_variables, unused_assignments)] fn main() { let my_option: Option<()> = None; if my_option.is_none() { - my_option.unwrap(); + // my_option.unwrap(); } let my_arr = &[ - -1, -2, -3 + -1, -2, -3, -4, -5, -6 ]; println!("My array! Here it is: {:?}", my_arr); - let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); + let my_empty_vec = vec![1, 2, 3, 4, 5]; println!("This Vec is empty, see? {:?}", my_empty_vec); let mut value_a = 45; let mut value_b = 66; // Let's swap these two! - value_a = value_b; - value_b = value_a; + //value_a = value_b; + //value_b = value_a; + std::mem::swap(&mut value_a, &mut value_b); println!("value a: {}; value b: {}", value_a, value_b); } diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index 2ba9e3f0..8ad4db71 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -7,25 +7,25 @@ // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + // Obtain the number of bytes (not characters) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { +fn byte_counter>(arg: T) -> usize { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn char_counter(arg: T) -> usize { +fn char_counter>(arg: T) -> usize { arg.as_ref().chars().count() } // Squares a number using as_mut(). // TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { +fn num_sq>(arg: &mut T) { // TODO: Implement the function body. - ??? + *arg.as_mut() = *arg.as_mut() * *arg.as_mut(); } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index 60911f3e..58c05469 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -40,10 +40,26 @@ impl Default for 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 -// I AM NOT DONE + impl From<&str> for Person { fn from(s: &str) -> Person { + + let persion: Vec<&str> = s.split(',').collect(); + if persion.len() < 2 || persion[0].len() == 0 { + return Person::default(); + } + + let name = persion[0].to_string(); + let age = match persion[1].parse::() { + Ok(r) => r, + _ => return Person::default() + }; + + Person { + name, + age + } } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index 34472c32..88b73ba2 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -31,7 +31,7 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE + // Steps: // 1. If the length of the provided string is 0, an error should be returned @@ -52,6 +52,26 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.len() == 0 { + return Err(ParsePersonError::Empty); + } + + let persion: Vec<&str> = s.split(',').collect(); + if persion.len() != 2 { + return Err(ParsePersonError::BadLen); + } + + if persion[0].len() == 0 { + return Err(ParsePersonError::NoName); + } + + let name = persion[0].to_string(); + let age = persion[1].parse::().map_err(ParsePersonError::ParseInt)?; + + Ok(Person { + name, + age + }) } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index 32d6ef39..52ecb648 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -27,7 +27,7 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE + // Your task is to complete this implementation and return an Ok result of inner // type Color. You need to create an implementation for a tuple of three @@ -41,6 +41,16 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + if tuple.0 > 255 || tuple.0 < 0 { + return Err(IntoColorError::IntConversion); + } + if tuple.1 > 255 || tuple.1 < 0 { + return Err(IntoColorError::IntConversion); + } + if tuple.2 > 255 || tuple.2 < 0 { + return Err(IntoColorError::IntConversion); + } + Ok(Self { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 }) } } @@ -48,6 +58,16 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + if arr[0] > 255 || arr[0] < 0 { + return Err(IntoColorError::IntConversion); + } + if arr[1] > 255 || arr[1] < 0 { + return Err(IntoColorError::IntConversion); + } + if arr[2] > 255 || arr[2] < 0 { + return Err(IntoColorError::IntConversion); + } + Ok(Self { red: arr[0] as u8, green: arr[1] as u8, blue: arr[2] as u8 }) } } @@ -55,6 +75,19 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + if slice[0] > 255 || slice[0] < 0 { + return Err(IntoColorError::IntConversion); + } + if slice[1] > 255 || slice[1] < 0 { + return Err(IntoColorError::IntConversion); + } + if slice[2] > 255 || slice[2] < 0 { + return Err(IntoColorError::IntConversion); + } + Ok(Self { red: slice[0] as u8, green: slice[1] as u8, blue: slice[2] as u8 }) } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 414cef3a..f4adc9c8 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -10,11 +10,11 @@ // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); - total / values.len() + total / values.len() as f64 } fn main() { diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs index 31076bb9..721b2efa 100644 --- a/exercises/iterators/iterators1.rs +++ b/exercises/iterators/iterators1.rs @@ -9,18 +9,18 @@ // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[test] fn main() { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2 assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3 assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 + assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4 } diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs index dda82a08..009f3262 100644 --- a/exercises/iterators/iterators2.rs +++ b/exercises/iterators/iterators2.rs @@ -6,7 +6,7 @@ // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + // Step 1. // Complete the `capitalize_first` function. @@ -15,7 +15,13 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => { + let mut s = first.to_uppercase().to_string(); + while let Some(v) = c.next() { + s.push(v); + } + s + } } } @@ -24,7 +30,11 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + let mut out: Vec = vec![]; + for v in words { + out.push(capitalize_first(v)); + } + out } // Step 3. @@ -32,7 +42,11 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + let mut out = String::new(); + for v in words { + out.push_str(&capitalize_first(v)); + } + out } #[cfg(test)] diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs index 29fa23a3..791fbe23 100644 --- a/exercises/iterators/iterators3.rs +++ b/exercises/iterators/iterators3.rs @@ -9,7 +9,7 @@ // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { @@ -26,23 +26,33 @@ pub struct NotDivisibleError { // Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. pub fn divide(a: i32, b: i32) -> Result { - todo!(); + if b == 0 { + return Err(DivisionError::DivideByZero); + } + + if a % b == 0 { + Ok(a/b) + } else { + Err(DivisionError::NotDivisible(NotDivisibleError { dividend: a, divisor: b })) + } } // Complete the function and return a value of the correct type so the test // passes. // Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { +fn result_with_list() -> Result, DivisionError> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27)).flatten().collect::>(); + Ok(division_results) } // Complete the function and return a value of the correct type so the test // passes. // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); + let division_results = numbers.into_iter().map(|n| divide(n, 27)).collect::>(); + division_results } #[cfg(test)] diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs index 79e1692b..5b4039d8 100644 --- a/exercises/iterators/iterators4.rs +++ b/exercises/iterators/iterators4.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num @@ -15,6 +15,11 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + match num { + 0 => 1, + 1 => 1, + _ => factorial(num - 1) * num + } } #[cfg(test)] diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs index a062ee4c..4089595d 100644 --- a/exercises/iterators/iterators5.rs +++ b/exercises/iterators/iterators5.rs @@ -11,7 +11,7 @@ // Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::collections::HashMap; @@ -35,7 +35,8 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + //todo!(); + map.iter().filter(|(_, v)| **v == value ).collect::>().len() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -54,7 +55,8 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + //todo!(); + collection.iter().flatten().filter(|(_, v)| **v == value ).collect::>().len() } #[cfg(test)] diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs index 678de6ee..eb0cbbaa 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + macro_rules! my_macro { () => { @@ -12,5 +12,5 @@ macro_rules! my_macro { } fn main() { - my_macro(); + my_macro!(); } diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index 788fc16a..7676448c 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -3,12 +3,13 @@ // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + fn main() { my_macro!(); } +#[macro_export] macro_rules! my_macro { () => { println!("Check out my macro!"); diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs index b795c149..1601800c 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -5,9 +5,10 @@ // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + mod macros { + #[macro_export] macro_rules! my_macro { () => { println!("Check out my macro!"); diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index 71b45a09..f73bcb2a 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -3,15 +3,15 @@ // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + #[rustfmt::skip] macro_rules! my_macro { () => { - println!("Check out my macro!"); - } + println!("Check out my macro!") + }; ($val:expr) => { - println!("Look at this other macro: {}", $val); + println!("Look at this other macro: {}", $val) } } diff --git a/exercises/smart_pointers/arc1.rs b/exercises/smart_pointers/arc1.rs index 3526ddcb..dd310749 100644 --- a/exercises/smart_pointers/arc1.rs +++ b/exercises/smart_pointers/arc1.rs @@ -21,7 +21,7 @@ // // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + #![forbid(unused_imports)] // Do not change this, (or the next) line. use std::sync::Arc; @@ -29,11 +29,11 @@ use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(numbers); let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = shared_numbers.clone(); joinhandles.push(thread::spawn(move || { let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); println!("Sum of offset {} is {}", offset, sum); diff --git a/exercises/smart_pointers/box1.rs b/exercises/smart_pointers/box1.rs index 513e7daa..d4bf71ea 100644 --- a/exercises/smart_pointers/box1.rs +++ b/exercises/smart_pointers/box1.rs @@ -18,11 +18,11 @@ // // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } @@ -35,11 +35,13 @@ fn main() { } pub fn create_empty_list() -> List { - todo!() + //todo!() + List::Nil } pub fn create_non_empty_list() -> List { - todo!() + //todo!() + List::Cons(1, Box::new(create_empty_list())) } #[cfg(test)] diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs index fcd3e0bb..fa016057 100644 --- a/exercises/smart_pointers/cow1.rs +++ b/exercises/smart_pointers/cow1.rs @@ -12,7 +12,7 @@ // // Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + use std::borrow::Cow; @@ -48,7 +48,8 @@ mod tests { let slice = [0, 1, 2]; let mut input = Cow::from(&slice[..]); match abs_all(&mut input) { - // TODO + Cow::Borrowed(_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -60,7 +61,8 @@ mod tests { let slice = vec![0, 1, 2]; let mut input = Cow::from(slice); match abs_all(&mut input) { - // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), } } @@ -72,7 +74,8 @@ mod tests { let slice = vec![-1, 0, 1]; let mut input = Cow::from(slice); match abs_all(&mut input) { - // TODO + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), } } } diff --git a/exercises/smart_pointers/rc1.rs b/exercises/smart_pointers/rc1.rs index 1b903469..313db7ca 100644 --- a/exercises/smart_pointers/rc1.rs +++ b/exercises/smart_pointers/rc1.rs @@ -10,7 +10,7 @@ // // Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE + use std::rc::Rc; @@ -61,17 +61,17 @@ fn main() { jupiter.details(); // TODO - let saturn = Planet::Saturn(Rc::new(Sun {})); + let saturn = Planet::Saturn(sun.clone()); println!("reference count = {}", Rc::strong_count(&sun)); // 7 references saturn.details(); // TODO - let uranus = Planet::Uranus(Rc::new(Sun {})); + let uranus = Planet::Uranus(sun.clone()); println!("reference count = {}", Rc::strong_count(&sun)); // 8 references uranus.details(); // TODO - let neptune = Planet::Neptune(Rc::new(Sun {})); + let neptune = Planet::Neptune(sun.clone()); println!("reference count = {}", Rc::strong_count(&sun)); // 9 references neptune.details(); @@ -93,12 +93,15 @@ fn main() { println!("reference count = {}", Rc::strong_count(&sun)); // 4 references // TODO + drop(earth); println!("reference count = {}", Rc::strong_count(&sun)); // 3 references // TODO + drop(venus); println!("reference count = {}", Rc::strong_count(&sun)); // 2 references // TODO + drop(mercury); println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference assert_eq!(Rc::strong_count(&sun), 1); diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index 80b6def3..2f8d15a0 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -8,7 +8,7 @@ // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::thread; use std::time::{Duration, Instant}; @@ -27,6 +27,7 @@ fn main() { let mut results: Vec = vec![]; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + results.push(handle.join().unwrap()); } if results.len() != 10 { diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index 62dad80d..2f3b7991 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -7,25 +7,26 @@ // Execute `rustlings hint threads2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::sync::Arc; use std::thread; use std::time::Duration; +use std::sync::RwLock; struct JobStatus { - jobs_completed: u32, + jobs_completed: RwLock, } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + let status = Arc::new(JobStatus { jobs_completed: RwLock::new(0) }); let mut handles = vec![]; for _ in 0..10 { let status_shared = Arc::clone(&status); let handle = thread::spawn(move || { thread::sleep(Duration::from_millis(250)); // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; + *(status_shared.jobs_completed.write().unwrap()) += 1; }); handles.push(handle); } @@ -34,6 +35,6 @@ fn main() { // TODO: Print the value of the JobStatus.jobs_completed. Did you notice // anything interesting in the output? Do you have to 'join' on all the // handles? - println!("jobs completed {}", ???); + println!("jobs completed {}", status.jobs_completed.read().unwrap()); } } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index 91006bbc..fb0b6def 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint threads3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE + use std::sync::mpsc; use std::sync::Arc; @@ -31,6 +31,8 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc1 = Arc::clone(&qc); let qc2 = Arc::clone(&qc); + let tx2 = tx.clone(); + thread::spawn(move || { for val in &qc1.first_half { println!("sending {:?}", val); @@ -42,7 +44,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { thread::spawn(move || { for val in &qc2.second_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + tx2.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } });