rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.21k stars 12.56k forks source link

Book contradicts itself #28862

Closed Pyriphlegethon closed 8 years ago

Pyriphlegethon commented 8 years ago

In chapter 2.3 Dining Philosophers the map function is used to call a closure for every philosopher. The closure however is only executed for its side effects (it doesn't actually calculate anything). The chapter on iterators however states that one shouldn't use map for side-effects, but simply use a for loop.

petrochenkov commented 8 years ago

The closure however is only executed for its side effects (it doesn't actually calculate anything).

How is that? The closures calculate thread handles which are then collected by collect().

steveklabnik commented 8 years ago

Thank you for the report!

Yes, @petrochenkov is correct. If we used a for loop here, we would drop each handle in turn, which would make things not paralell. The purpose is to map closures to handles.

Maybe we can make this more clear somehow?

Pyriphlegethon commented 8 years ago

We wouldn't necessarily drop the handles, we could still insert them into a vector. But you're correct, the map does in fact calculate something. Maybe we should add that using map without using its result is bad? Although the compiler will complain about that anyhow.

sfackler commented 8 years ago

Just using map alone is bad because it doesn't actually work :). The thing the book is warning against doing is something like

things.iter().map(|thing| thing.update()).count();

Where the call to count consumes the iterator, making all of the update calls.

steveklabnik commented 8 years ago

Yeah, given that the compiler gives a warning if we remove it, I think that we can chalk this one up to misunderstanding. If anyone wants to somehow improve this, please send a PR. Thanks!