rust-lang / rust-lang/rust-clippy

Duration's constructors should not trigger or_fun_call

Open
#7,483 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Lint name: or_fun_call

I tried this code:

let mut tick_rate = cli.time.unwrap_or(Duration::from_secs(1));

I expected to see this happen: nothing, since Duration::from_secs is a const fn. it's cheaper to use unwrap_or than unwrap_or_else, which requires creating a closure. I understand the rationale for closing #6943: Clippy can't be certain that the function will be evaluated at compile time. However, I would argue that since Clippy can neither be certain that the function will be evaluated at runtime, it should not make a recommendation one way or the other in this case. This is a case where the programmer probably knows more than Clippy does.

Instead, this happened:

warning: use of `unwrap_or` followed by a function call
   --> src/main.rs:358:34
    |
358 |     let mut tick_rate = cli.time.unwrap_or(Duration::from_secs(1));
    |                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| Duration::from_secs(1))`
Meta
  • cargo clippy -V: e.g. clippy 0.0.212 (f455e46 2020-06-20)
  • rustc -Vv:
rustc 1.55.0-nightly (952fdf2a1 2021-07-05)
binary: rustc
commit-hash: 952fdf2a1119affa1b37bcacb0c49cf9f0168ac8
commit-date: 2021-07-05
host: x86_64-unknown-freebsd
release: 1.55.0-nightly
LLVM version: 12.0.1

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 reproducing the or_fun_call warning with the Duration::from_secs example using cargo clippy, then trace the lint named in the report. Determine how constructor calls are classified and update the relevant tests so this case no longer recommends unwrap_or_else; the existing warning should remain covered for applicable function calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.