rust-lang / rust-lang/rust-clippy
New lint: Prefer `.unwrap_or(0)` over `.unwrap_or_default()`
Open
@nik-rev is already working on this.
Since May 11, 2025.
A-lint
C-enhancement
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
This lint disallows usages of the methods using Default trait when there is an alternative, explicit type for a select number of types which are deemed to have an "obvious" default implementation as well as being easy to type
Methods such as:
Option::unwrap_or_default->Option::unwrap_orResult::unwrap_or_default->Result::unwrap_orEntry::or_default->Entry::or_insert
Types affected:
- numbers:
0or0.0 &str:""bool:falsechar:'\0'Option<T>:None
I would avoid implementing this for even slightly more involved types like the NonZero family as:
- more typing involved
- has to bring the respective type into scope
category: complexity
lint name: or_default_for_simple_type
Advantage
- Reduces cognitive complexity. You have to think about the type less
- You don't have to know the type. It is useful when reviewing code on github
- Is more concise to type
- Everyone knows what the defaults for these types are
Drawbacks
- Some people may prefer using
Defaulttrait
Example
let a: Option<u8> = None;
let b = a.unwrap_or_default();
Could be written as:
let a: Option<u8> = None;
let b = a.unwrap_or(0);
.
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.