Suggestion for 'try_collect'
⚓ Rust 📅 2026-01-16 👤 surdeus 👁️ 5First and foremost, I apologize if this is not the right channel for this discussion/suggestion of feature or if something similar has already been discussed previously.
In Rust we have collect. An issue of it is, that for example, if we are OOM we might fail and thus get an abort (or panic if you configure it to do so). There are some scenarios where this is not ideal, for example scenarios where you are able to free some memory and then retry the operation for example (let say that you have a limited pool of memory for layout X and multiples thereof which you control for example on an embedded system), or when you absolutely need to keep a service running still until a certain moment (for example, you don't accept new connections, keep the current ones alive and ends the service only when all connections have been dropped).
For this, it would be interesting, when working with iterators, to have a try_collect method (and as such, a Trait or whatever on how this is implemented for the collect method). It should then return a Result<CollectionType, Error>. One of the nice things is that something as such would allow for seamless collection keeping a similar interface for fixed sized arrays, as for example:
collection.iter().filter(|item|
/*yada yada code if some condition met, Some(item) else None */
).try_collect<[T : N]>()
}
If N and the amount of items that have been filtered do not match, then collection would fail. I am aware that are multiple ways of avoiding this scenario that avoid non fallible operations, such as, for example, creating a Vector first and trying to preallocate the space needed or having a fixed sized array of MaybeUninit, but I would argue that having a similar interface would allow for more ergonomic and readable code, keeping code, for the lack of a better word, somewhat 'standardized'.
6 posts - 4 participants
🏷️ Rust_feed