Creating a vector with reserved space

A small feature request, maybe something like Vec::new_reserved(size: usize) could be useful? Sometimes when extracting data in code I keep writing long structures like:

// This
{ 
    let mut v = vec![];
    v.reserve(space_hint);
    v
}

// Can be replaced with
Vec::new_reserved(space_hint)

They are not very readable and might be useful for others too. It might come in handy for iterators too, since now ones that have a size_hint can request the required amount of space when collecting:

Vec::with_capacity?

10 Likes

:facepalm:

Right, sorry lol, could not find this in the docs. Well, at least it will be helpful to whomever finds this post next.

EDIT: Maybe this should a clippy warning then?

4 Likes

Sounds like a reasonable idea to me. I tried searching for pre-existing proposals in the relevant issue tracker and didn’t see anything so far. Feel free to open a new one ^^

2 Likes

Great minds think alike?

I guess that one is specifically for zero-initialized data, but it's probably related.

2 Likes

Looks like maybe this is about using resize, not reserve?

BTW, libstd is lacking Vec::try_with_capacity(). Vec::new(); vec.try_reserve()? is the only non-aborting option.

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.