Simplify if/else that returns opposite boolean literals

This product is not supported for your selected Datadog site. ().
このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください

Metadata

ID: rust-code-quality/needless-bool

Language: Rust

Severity: Warning

Category: Code Style

Description

An if/else expression that returns true in one branch and false in the other is equivalent to the condition itself (or its negation). The boolean literal branches are redundant and add noise without adding clarity.

How to remediate?

Replace the if/else with the condition directly:

// Before
if x > 0 { true } else { false }

// After
x > 0

// Before
if x > 0 { false } else { true }

// After
!(x > 0)

Non-Compliant Code Examples

fn check_positive(x: i32) -> bool {
    if x > 0 { true } else { false }
}

fn check_negative(x: i32) -> bool {
    if x > 0 { false } else { true }
}

fn is_admin(role: &str) -> bool {
      if role == "admin" { true } else { false }
}

Compliant Code Examples

fn same_branch(x: i32) -> bool {
    if x > 0 { true } else { true }
}

fn non_literal(x: i32) -> bool {
    if x > 0 { x > 1 } else { false }
}

fn no_else(x: i32) -> bool {
    if x > 0 { return true; }
    false
}

fn has_permission(role: &str, action: &str) -> bool {
      if role == "admin" { log_access(action); true } else { false }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

シームレスな連携。 Datadog Code Security をお試しください