Skip to content

Python-like chained comparison operators #77823

Closed
@mayabyte

Description

@mayabyte

Python allows chaining comparison operators as a helpful shorthand:

if a < b < c:  # equivalent to (a < b and b < c)
    ...

However Rust explicitly disallows this:

fn main() {
    5 < 10 < 15
}

// error: comparison operators cannot be chained
// --> chain.rs:2:5
//  |
// 2 |   5 < 10 < 15
//  |     ^    ^
//  |
// help: split the comparison into two
//  |
// 2 |   5 < 10 && 10 < 15
//  |          ^^^^^
//
// error: aborting due to previous error

rust-lang/rfcs#558 seems to be the source of this explicit disallow, with the primary motivation being confusing behavior: a < b < c used to be interpreted as (a < b) < c, resulting in a type error. The RFC also claims this would allow implentation of Python-like chained comparison operators in the future. Is there any motivation not to add these Python-like chained comparison operators into Rust? Given that the syntax for it has been a compiler error since pre-1.0, it doesn't seem like it could be a breaking change. Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions