rust-lang / rust-lang/rust-clippy

warn on casting integer division to a float

Open
#8,251 6 comments 1 reaction 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

Maybe Clippy should warn about dividing two integers and then casting to a float? For example, (4/3) as f64 probably does not do what the author intends. Clippy could suggest instead writing 4f64 / 3f64.

This could perhaps be extended to division of integer variables or expressions, although perhaps in that case there might be more cases where it's intentional?

I'm not sure if this is a common-enough mistake to be worth a lint.

I read this post describing someone's experience using Rust for the first time and making this mistake: https://blog.singleton.io/posts/2022-01-02-raytracing-with-rust/#:~:text=let%20aspect_ratio%20%3D%20(800%20/%20600)%20as%20f64

Lint Name

cast_integer_division_to_float

Category

suspicious

Advantage

This may be a bug: the division will be done in integers, when the user might intend to get a fractional result.

Drawbacks

False positives? Perhaps bugs from this mistake will often be obvious?

Example
let r = (800 / 600) as f64;
let a = 13;
let b = (a / 3) as f64;

Could be written as:

let r = 800.0 / 600.0;
let a = 13;
let b = (a as f64) / 13;

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 reviewing existing Rust Clippy lints in the suspicious category and compare their handling of integer division followed by a float cast. Use the examples in the issue to define the intended cases and suggested rewrite, then add coverage for the supported forms and confirm the lint's false-positive behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 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.