Description
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![];