When to use vec! instead of Vec::new()?
henrywallace opened this issue · comments
advent-of-code/aoc03/src/main.rs
Line 26 in d5e3fe3
I think I pretty much always use vec![]
. I can't think of any specific instance where I'd want to use Vec::new
, unless I wanted to use it as a function value. e.g., if you have
fn build_a_vec(build: impl Fn() -> Vec<i32>) {
let vector = build();
// do something with vector
}
fn main() {
build_a_vec(Vec::new);
}
But even then, that's not code I can remember writing.
I believe the choice between vec![]
and Vec::new
is almost entirely stylistic. The former is more flexible, so it tends to be what folks use.
Note that in the code you referenced, I did include the type, Vec<Claim>
, which I believe is optional in that context. I include the type sometimes to make the code clearer. It's a judgment call. :-)