Basic questions about a code example

Why do I need count here and *count on next line? See
https://github.com/mvolkmann/rust-poker/blob/master/src/lib.rs#L169

Why does the compiler think this function is never used? See
https://github.com/mvolkmann/rust-poker/blob/master/src/lib.rs#L302

This is because the closure argument to Iterator::any consumes its argument (FnMut(Self::Item) -> bool), while the closure argument to Iterator::filter takes a shared reference (FnMut(&Self::Item) -> bool).

(The reason for the differing signatures here is that once you call .any() on an iterator you can't do anything else with it, so you might as well consume the items you're iterating over; whereas .filter() returns another iterator over the same item type, so it can't consume any of the items in case it needs to pass them along.)

1 Like

The answer to your first question can be given solely by examining the documentatino of HashMap::values(), Iterator::any() and Iterator::filter() – the Item type of HashMap<K, V>::values() is &V, so when you filter() it, the closure will be passed elements of type &&V, because filter adds a layer of indirection. Meanwhile, any passes the closure the elements itself (which again have type &V in your case), without referencing them yet again.

The answer to your second question is: regular (non-test) builds don't build #[test] and #[cfg(test)] items at all – so in a non-test build, your function is unused, because conditional compilation plainly removes its caller.

4 Likes

Is there something I can add to tell the compiler that the suit_name function will be used so that I don't see a warning about it every time I run the app or the tests?

You could stick an #[allow(unused)] on it. More conventionally, you can put all the code that's only used in tests in a tests submodule and put #[cfg(test)] on that, so that the compiler doesn't even see it except when testing.

1 Like

In this case the function isn't intended to only be used by tests. It's just that the app doesn't use it yet. So I guess I should add #[allow(unused)] temporarily until the app needs it.

1 Like

I prefer to leave the warnings (unless there are a gazillion of them) as a reminder, but your memory is probably better than mine.

The problem comes after you've implemented the code that uses the function. If you fail to remove the #[allow(unused)] and later make a change to no longer use the function, you won't get the warning that you might want.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.