4 ms·
Depending on how you write it, iterators are much better at this since most iterator methods produce iterators with size hints. If you use "take" for example,
by sgeisenh 4y ago
Depending on how you write it, iterators are much better at this since most iterator methods produce iterators with size hints.
If you use "take" for example, collect should do the right thing: https://doc.rust-lang.org/src/core/iter/adapters/take.rs.html#58 https://doc.rust-lang.org/src/core/iter/adapters/take.rs.htm...
- tialaramex 4y agoMere hints aren't enough for collect() It will only care about your hints if you implement the unsafe trait TrustedLen (which promises those hints are correct) Take is indeed TrustedLen if the Iterator it's taking from is TrustedLen (as in this case it can be sure of the size hint) If you get to ~100 via some means other than take()ing 100 of them, chances are you don't have TrustedLen as a result.
- Alexendoo 4y agoTrustedLen will mean it can safely take the upper bound, but Vec for example will still use the lower bound of the hint when something isn't TrustedLen https://doc.rust-lang.org/src/alloc/vec/spec_from_iter_nested.rs.html https://doc.rust-lang.org/src/alloc/vec/spec_from_iter_neste...
- tialaramex 4y agoOoh nice, I hadn't seen that. OK, so there are probably places where I assumed the iterator won't do as nice a job of collect() as I did manually but I was wrong. I wonder how the hell I didn't see that when I was tracking down how collect() ends up caring about TrustedLen. Thanks.