Rust: Number declaration underscores allow any arbitrary pattern

Created on 31 Oct 2016  路  8Comments  路  Source: rust-lang/rust

I noticed number declarations using the underscore markers are very permissive eg.

fn main() {
    let i = 1_0000__00_0;
    println!("{}", i);
}

Compiles fine. I realise this probably isn't a big deal but if someone's number, using those underscores, breaks from the

000_000

Kind of pattern, it's probably likely to be an error? Maybe there are some cases where the user would like to initialise a number in such a way for bit level operations though, I'm not very familiar with that so I can't comment on it but it might be relevant.

Most helpful comment

Sounds like a clippy lint.

All 8 comments

I'm not that familiar with Rust, but with most programming languages underscores can go anywhere between two digits. The only places they can't go are directly after (123_), before, (_123), or between or after a prefix (0x7b).

This is described in the reference:

An integer literal has one of four forms:

  • A decimal literal starts with a decimal digit and continues with any mixture of decimal digits and underscores.

Sounds like a clippy lint.

I wonder what the initial motivation was? It has a certain simplicity. Note that there will be users of 1_00_00_000 and so on, see https://en.wikipedia.org/wiki/Crore

Another example: let price_in_cents = 14_95; (aside from not using a big decimal and a newtype, this might be legit code).

Seems like there are some legitimate cases for breaking from 000_000 style. What about the use of successive underscores? Eg. 1__0?

0b1111_1111__1111_1111___1111_1111__1111_1111

Yeah, I'm going to go ahead and close -- if anyone's interested, feel free to open an issue at Clippy, this is more in their lint territory.

Was this page helpful?
0 / 5 - 0 ratings