Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add lint for empty vec! invocation #12774

Open
andrewbanchich opened this issue May 7, 2024 · 2 comments
Open

add lint for empty vec! invocation #12774

andrewbanchich opened this issue May 7, 2024 · 2 comments
Labels
A-lint Area: New lints

Comments

@andrewbanchich
Copy link
Contributor

What it does

instead of calling vec![] to create an empty vec, use Vec::new(). the vec! macro's purpose is for adding any number of items to a vec in an ergonomic and optimized way, so there is no advantage to creating an empty vec with a macro.

vec![] will expand to Vec::new() anyway, so just write Vec::new().

Advantage

  • remove unnecessary macro call for times you just need an empty vec
    -- not sure if this counts as a micro/nano-optimization since there no more macro expansion
    -- at the very least, i think it's good to reserve macros for only when they provide some value

Drawbacks

No response

Example

let nums: Vec<usize> = vec![];

Could be written as:

let nums: Vec<usize> = Vec::new();
@andrewbanchich andrewbanchich added the A-lint Area: New lints label May 7, 2024
@matthiaskrgr
Copy link
Member

Note that there have been cases where the macro actually generated better code than vec::new()

rust-lang/rust#54475

@Nilstrieb
Copy link
Member

I don't think this should be more than a restriction lint. There is nothing clearer and more readable about new imo, especially when there are several other uses of the vec macro with values in the same function, it's more consistent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

3 participants