Skip to content

trailing_empty_array in tests #13837

Closed
@TomFryersMidsummer

Description

@TomFryersMidsummer

Summary

Empty arrays are not unreasonable in test code. I noticed this with proptest-generated structs, but it applies equally to user-written code, so I think it makes sense to allow this for all test code, rather than getting proptest to put #[allow(clippy::trailing_empty_array)] on its generated code.

Lint Name

trailing_empty_array

Reproducer

I tried this code:

pub struct Friend {
    age: u8,
}

pub trait Friendly<const N: usize> {
    fn friends(&self) -> &[Friend; N];

    fn oldest_friend(&self) -> Option<&Friend> {
        self.friends().iter().max_by_key(|x| x.age)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn oldest_empty_is_none() {
        struct Michael {
            friends: [Friend; 0],
        }

        impl Friendly<0> for Michael {
            fn friends(&self) -> &[Friend; 0] {
                &self.friends
            }
        }

        let michael_the_loneliest_boy_in_town = Michael { friends: [] };

        assert!(michael_the_loneliest_boy_in_town.oldest_friend().is_none());
    }
}

I saw this happen:

$ clippy-driver --crate-type=lib -W clippy::trailing_empty_array --test a.rs
warning: trailing zero-sized array in a struct which is not marked with a `repr` attribute
  --> a.rs:19:9
   |
19 | /         struct Michael {
20 | |             friends: [Friend; 0],
21 | |         }
   | |_________^
   |
   = help: consider annotating `tests::oldest_empty_is_none::Michael` with `#[repr(C)]` or another `repr` attribute
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#trailing_empty_array
   = note: requested on the command line with `-W clippy::trailing-empty-array`

warning: 1 warning emitted

I expected to see this happen: [no error]

Version

rustc 1.85.0-nightly (c26db435b 2024-12-15)
binary: rustc
commit-hash: c26db435bf8aee2efc397aab50f3a21eb351d6e5
commit-date: 2024-12-15
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.5

and

rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1

Additional Labels

No response

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions