rust-lang / rust-lang/rust-clippy

New lint: Prefer `.unwrap_or(0)` over `.unwrap_or_default()`

Open
#14,779 1 comment 3 reactions 1 assignee View on GitHub

@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_or
  • Result::unwrap_or_default -> Result::unwrap_or
  • Entry::or_default -> Entry::or_insert

Types affected:

  • numbers: 0or 0.0
  • &str: ""
  • bool: false
  • char: '\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 Default trait
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.