rust-lang / rust-lang/rust-clippy

Clippy suggests an unintuitive fix

Open
#9,964 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Summary

Clippy's suggested fix for returning 1 or 0 from an if statement is unintuitive

Reproducer

writing code like

if opt.is_some() {
    1
} else {
    0
}

leads clippy to suggest usize::from(opt.is_some()), i.e. coercing a boolean into an integer. It is not obvious to me that a boolean coerced into an integer will yield 0 for false and 1 for true. I'm not even sure why rust implements this From.

I've settled on opt.map_or(0, |_| 1) in order to avoid the lint while also still being clear about the output values.

Version
rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: x86_64-unknown-linux-gnu
release: 1.65.0
LLVM version: 15.0.0
Additional Labels

No response

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 running the Rust reproducer with Clippy and identify which lint emits the usize::from(opt.is_some()) suggestion. Read that lint's existing tests and suggestion handling; done means the recommended fix is addressed so the boolean-to-integer behavior is clear to users, with regression coverage for the reproducer.

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.