Intervening spaces are allowed in negative numeric literals?

Was very surprised to find that spaces are allowed between the minus and the digits in a literal. Neither rustc nor clippy contains. Only found this because I had a horrible typo in an if test:

fn main() {
    // Spaces seem to be OK between the minus and the number.
    let x = -   3;

    // Which can lead to a hellish typo-bug.
    let a = 30;
    if a >- 150 {
        println!("Not what I expected");

Is this a known thing? Do you think I should report it as a suggested clippy lint?

1 Like

What languages do you know of that reject this? Just tried C, C++, Python, JS and Java/IDEA and none of them complained.

There’s no ambiguity in terms of how the code gets parsed, so it makes sense that it’d be allowed (bear in mind that - is an operator that applies to the literal, it’s not part of the literal).

That said, = and - being right next to each other on the keyboard makes this pretty easy to run into, so I could see a Clippy lint maybe being a good idea!


That’s a good point @mrec. I hadn’t considered how other languages behave. My excuse is that I cannot remember ever making this error before :slight_smile: and it took me over an hour to find it in my actual code.

I wasted enough time on this to make it at least worth a suggestion. I’ll log an issue and see what they say.

1 Like

Consider running rustfmt more often – I know some people have their editors do it on save – because it will reformat it to if a > -150 { as one would expect, which should make it easier to notice.


For the record, issue raised here

Note that the Rust syntax considers -1i8 as an application of the unary minus operator to an integer literal 1i8 , rather than a single integer literal.

^ from rust reference manual.

Either solution from @scottmcm or @17cupsofcoffee should be fine. Especially having rustfmt enabled in editor for every “save”.

1 Like

Yes, this is the pertinent detail. An expression such as -4 is not a single token but two, and like any two tokens, they can be separated by whitespace. It is somewhat surprising, but negative literals don’t actually exist!