For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/rust-code-quality/identical-operand-comparison.md. A documentation index is available at /llms.txt.

Binary expression with identical operands on both sides

This product is not supported for your selected Datadog site. ().

Metadata

ID: rust-code-quality/identical-operand-comparison

Language: Rust

Severity: Error

Category: Error Prone

Description

Using the same operand on both sides of a binary operator is almost always a bug, typically a copy-paste error where the wrong variable was used.

  • With ==, <=, or >= the expression is always true.
  • With !=, <, or > the expression is always false.
  • With &&, ||, &, |, or ^ the result is redundant.
  • With - the result is always 0; with / the result is always 1.

Example

// Before — always evaluates to true, likely a bug
if timeout == timeout {
    return Err("timed out");
}

// After — compare against the intended value
if elapsed == timeout {
    return Err("timed out");
}

Non-Compliant Code Examples

fn always_true(a: i32) -> bool {
    a == a
}

fn always_false(a: i32) -> bool {
    a != a
}

struct Point { x: i32, y: i32 }

fn field_always_true(p: Point) -> bool {
    p.x == p.x
}

fn redundant_and(a: bool) -> bool {
    a && a
}

fn always_zero(a: i32) -> i32 {
    a - a
}

fn always_false_lt(a: i32) -> bool {
    a < a
}

fn always_true_gte(a: i32) -> bool {
    a >= a
}

Compliant Code Examples

fn compare_different(a: i32, b: i32) -> bool {
    a == b
}

fn compare_fields(x: i32, y: i32) -> bool {
    x != y
}

struct Point { x: i32, y: i32 }

fn compare_field_different(p: Point, q: Point) -> bool {
    p.x == q.x
}

fn bitwise_different(a: u32, b: u32) -> u32 {
    a & b
}

fn func_call_not_flagged(mut v: Vec<i32>) -> bool {
    v.pop() == v.pop()
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security