rust-lang / rust-lang/rust-clippy

Lint: function calls when using .expect on Result should be unwrap_or_else

Open
#8,820 0 comments 0 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

Catches use of non-const function calls (like the format macro) within a expect method call on Result.

This should be replaced by unwrap_or_else, in order to avoid work being performed on the happy path.

Lint Name

function_call_in_expect

Category

perf

Advantage
  • The function called in the .expect call will be evaluated even when the method will not panic
  • Using unwrap_or_else avoids evaluation unless the method is called

This is particularly relevant when working with allocating functions / macros, like format!

Drawbacks

This is a performance micro-optimization, and makes your code slightly uglier.

Detecting whether or not a function is being used in a const way (as opposed to "if it could be const") may not be trivial. If this can't be done, then there are false positives when const functions being called within the .expect.

Example
        .expect(bevy_manifest.get_path(crate::BEVY_CREVICE))

Could be written as:

        .unwrap_or_else(|| bevy_manifest.get_path(crate::BEVY_CREVICE))

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 by searching the rust-clippy repository for function_call_in_expect and related Result or .expect lint tests. Use the supplied .expect and .unwrap_or_else examples to define the expected diagnostic, and investigate how to distinguish non-const calls from const calls. Done means the lint handles the intended performance case without false positives from const calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.