Skip to content

Warn the user about side effects when creating empty arrays and vectors #6439

Closed
@woodruffw

Description

@woodruffw

What it does

Both the vec![] macro and the array bulk-initializer syntax ([T; N]) allow the programmer to initialize an empty container, i.e. one that contains no copies of T.

However, both syntaxes still invoke T at least once, meaning that code like this:

let empty = vec![something(); 0];

can have unexpected side effects when something is called.

Here's a proof of concept with both a vector and an array:

fn side_effect() -> String {
    println!("side effect!");

    "foo".into()
}

fn main() {
    println!("before!");

    let x = vec![side_effect(); 0];
    
    let y = [side_effect(); 0];

    println!("{:?}, {:?}", x, y);
}

produces:

before!
side effect!
side effect!
[], []

What does this lint do?

Warns the user that empty initializations of vectors and arrays can cause side effects.

Categories (optional)

  • Kind: correctness

Justification: T's initialization is useless, since the user can't access it (they're declaring an empty container, after all) and it ends up being dropped immediately anyways.

What is the advantage of the recommended code over the original code

Avoids unexpected side effects and avoids a useless allocation.

Drawbacks

None.

Example

let x = vec![thing(); 0];

Could be written as:

let x = vec![];

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions