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-ifThe [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.
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
- too_many_linesChecks for functions with a large amount of lines
- missing_errors_docChecks the doc comments of publicly visible functions that return a Result type and warns if there is no # Errors section
- must_use_candidateChecks for public functions that have no #[must_use] attribute, but return something not already marked must-use, have no mutable arg and mutate no statics
- assert_is_emptyChecks assertions that only test whether a supported value is empty. The lint handles assert! and debug_assert! calls on strings, slices, arrays, and Vec
- assigning_clonesassigning the result of `Clone::clone()` may be inefficient
- borrow_as_ptrborrow as raw pointer
- case_sensitive_file_extension_comparisonscase-sensitive file extension comparison
- cast_losslesscasts from `u8` to `u64` can be expressed infallibly using `From`
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?