Email me

Clippy lints / Pedantic

Clippy lint · Pedantic · checked with Clippy 0.1.99

clippy::bool_to_int_with_if: Instead of using an if statement to convert a bool to an int, this lint suggests using a from() function or an as coercion

What it meansInstead of using an if statement to convert a bool to an int, this lint suggests using a from() function or an as coercion. It is in the pedantic group and off by default.

Does it matter?

Coercion or from() is another way to convert bool to a number. Both methods are guaranteed to return 1 for true, and 0 for false. See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E

Stricter lints with some false positives. Off by default; opt in with clippy::pedantic.

How to fix it

Clippy can fix this one for you: run cargo clippy --fix (add --allow-dirty if you have uncommitted changes). Review the diff before you commit.

Flagged

if condition {
    1_i64
} else {
    0
};

Write this instead

i64::from(condition);

Turn it off, or on

It is off by default. To use it, set it to warn or deny:

Whole crate (Cargo.toml)

[lints.clippy]
bool_to_int_with_if = "warn"

In code

#![warn(clippy::bool_to_int_with_if)]

One run

cargo clippy -- -W clippy::bool-to-int-with-if

The [lints] table needs Rust 1.74 or newer. In a workspace, put it under [workspace.lints.clippy] and add [lints] workspace = true to each member.

Pedanticgroup
allowdefault level
yesfixed by cargo clippy --fix
1.65.0added in Rust

Clippy's own documentation

What it does

Instead of using an if statement to convert a bool to an int, this lint suggests using a from() function or an as coercion.

Why is this bad?

Coercion or from() is another way to convert bool to a number. Both methods are guaranteed to return 1 for true, and 0 for false.

See https://doc.rust-lang.org/std/primitive.bool.html#impl-From%3Cbool%3E

Example

if condition {
    1_i64
} else {
    0
};

Use instead:

i64::from(condition);

or

condition as i64;

From the Clippy lint list (0.1.99), part of the Rust project, MIT or Apache-2.0. Official entry.

Related lints

All 847 Clippy lints · Rust compiler errors · Cargo.toml checker

Up next

Related lintclippy::too_many_linesChecks for functions with a large amount of linesRead it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ