CleanCut/ultimate_rust2

Thread_channels challenge question

Dajamante opened this issue · 5 comments

Can you kindly have a look at that when your time allows?

https://github.com/Dajamante/Rustbook/blob/c81d0d2d33431eb7af810dfbd22145a66c95b08d/threads_channels/src/main.rs#L53

My second receiver channels does not receive any message. The compiler gives me a faire warning:


88 | /         child_rx2
89 | |             .into_iter()
90 | |             .map(|m| info!("Message dropped {}", m));
   | |_____________________________________________________^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: iterators are lazy and do nothing unless consumed

Thank you a lot in advance!

I'm afraid that the repository you linked to is not public, so I am unable to see most of your code.

However, from the error you pasted it seems clear what your problem is! Iterator adaptors like .map() produce new iterators. Iterators don't actually do anything until you consume them with an iterator consumer. One thing you could do above is add to the end of line 90 a final call to an iterator consumer like .for_each( ... ). For example:

child_rx2
    .into_iter()
    .map(|m| info!("Message dropped {}", m))
    .for_each(|x| {});

Notice that the closure in the .for_each doesn't do anything with the value receives from .map, but since .for_each is a consumer it activates the chain of iterators to make them all do the iteration and the side effects in .into_iter() (receiving from a channel) and .map (printing your message) will now happen.

You probably want to go one step further, though! .map is used to transform one value into another so you can use the transformed value. You aren't actually using any return value of the .map -- you're just using it to produce a side effect (print a message). In this case, you can go straight to .for_each which is an iterator consumer that gives you access to the value so you can use it for side effects:

child_rx2
    .into_iter()
    .for_each(|m| info!("Message dropped {}", m));

Give that a try and please let me know if you have any other questions!

Dear Nathan,
Thank you for the thorough explanation! It is working much more like expected (half of the messages are printed depending on sleep).
But the info! message never gets through. Why can that be?
Obviously all threads are accounted for, since I join in the end?

I also made the repo public if you want a look :): https://github.com/Dajamante/Rustbook/blob/ultimate_rust_intermediairy/threads_channels/src/main.rs

But the info! message never gets through. Why can that be?

Most likely it is because the default log level for env_logger is error. Have you tried running it with something like this?

RUST_LOG=info cargo run

Oh of course! Now I see everything as it should! Thanks for being here 🥇 !

My pleasure. 😄