rust-lang / rust-lang/rust-clippy

Suggest replacing `.unwrap_or_else(|| panic!("..."))` with `.expect("...")` on `Option<T: Debug>`

Open
#11,271 2 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Makes this roundabout way of writing .expect actually an expect call where it's feasible.

Advantage

The code is shorter and more straightforward in what it does, and IMHO more idiomatic.

Drawbacks

The parameter to expect is evaluated even when it doesn't end up being used.
Cf. unwrap_or vs. unwrap_or_else.
Not a big deal for literals, but could be significant in rare cases.

Example

This is a straight-up real-world example. I can trim it down upon request.

                full_output.platform_output.cursor_icon = player
                    .ui()
                    .downcast_ref::<DesktopUiBackend>()
                    .unwrap_or_else(|| panic!("UI Backend should be DesktopUiBackend")) // <--
                    .cursor();

(https://github.com/ruffle-rs/ruffle/blob/2621dd78eefab17e98dc03fafa25ed421784a712/desktop/src/gui/controller.rs#L213)

Could be written as:

                full_output.platform_output.cursor_icon = player
                    .ui()
                    .downcast_ref::<DesktopUiBackend>()
                    .expect!("UI Backend should be DesktopUiBackend") // <--
                    .cursor();

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.

Research direction

Start with the linked example in desktop/src/gui/controller.rs and compare the shown unwrap_or_else/panic form with the proposed expect call. Then locate the relevant Clippy lint entry point and tests; done means the lint handles feasible Option<T: Debug> cases and covers the transformation.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.