rust-lang / rust-lang/rust-clippy
Add a lint for `NonZero::new(0)` literal type footgun
@Bishops-exe is already working on this.
Since Sep 12, 2026.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Detect if any new() constructor for NonZeroX variant (NonZeroU8/16/32/64/128/size NonZeroI8/16/32/64/128/size) or any NonZero variant where T is any of the Signed or Unsigned integer types is set to 0 and throw an error.
let footgun: NonZeroU16 = NonZeroU16::new(0).unwrap();
Will only fail and panic at run time when this code branch is reached.
Advantage
- Warns you from effectively typing panic! into your code.
Drawbacks
No response
Example
let footgun: NonZeroU16 = NonZeroU16::new(0).unwrap();
(The key component is any 'NonZeroX::new(0)' should trigger this, the rest is irrelevant to the lint.)
Could be written as:
panic!("Crash my program please.");
//NonZero type set to zero literal.
Comparison with existing lints
No response
Additional Context
Currently NonZero types are unergonomic, this should reasonably be something built into the language itself to allow you to declare foo: NonZeroU16 = 5; at compile time without needing to make a new() call at all but it is necessary for now.
At all levels of optimization except none the compiler does optimize the .unwrap() away to its logical result.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.