Array-expression or type initialized with zero lengthRS-W1096
Array-expressions (or array-types) may be initialized with the repeat syntax,
[expr; N]
, to create an array of N
elements, where each element is expr
.
When using this syntax with N
set to 0
, expr
is evaluated, but the
resulting array is just []
. Similarly, for zero-sized array-types, the new
type created is the empty-array type: []
, which does not have much practical
use.
If the zero-sized array expression is intentional, consider moving the expr
outside the array-expression, and replacing the array-expression with the empty
array: []
.
If the zero-sized array type is being used as marker type, consider using
std::marker::PhantomData
instead, whose intention is much clearer.
Another reason to use PhantomData
is, that it doesn't force T
bound requirements,
as no instance of T
is actually part of the type.
Bad practice
struct Empty<T>([T;0]);
fn f() {
let mut arr = [0_u32; 0];
for x in &mut arr {
x = input();
}
}
Recommended
use std::marker;
struct Empty<T>(PhantomData<T>);
fn f() {
let mut arr = [0_u32; 10];
for x in &mut arr {
x = input();
}
}