Is there a function to set the size hint of an iterator?

Hi, I'm still new to the language and I have a question about iterators.
I'm using the from_fn function to generate an iterator and then I collect the values into a Vec. But since size_hint() is not implemented by the iterator retuned from from_fn, the default value (zero) is retuned and the Vec is not preallocated, right? If this is the case, how can I improve the performance of collect()?

Just write a struct and an impl Iterator for it, instead of using from_fn() at all.

You could write a wrapper that forwards next() but provides its own size_hint(), but that would be almost always more troublesome than just implementing the Iterator, since size_hint() must update as items are consumed from the iterator.

1 Like

Thanks for the answer. I just wanted to know what was the best way to do it, or if there was a function which could set the size, something like fn set_size(usize) -> IterWithSize.

There's no function to set the size hint of an iterator. The easiest way to ensure that it is preallocated is to do this instead of using collect:

let mut new_vec = Vec::with_capacity(size);
new_vec.extend(your_iterator);
2 Likes

Here's a comment from me on why this doesn't exist: https://github.com/rust-lang/rust/issues/68995#issuecomment-588569824

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.