Multiline integer literals in Rust

I have the following integer literal:

let centre: u64 = 0b00000000_00000000_00111100_00111100_00111100_00111100_00000000_00000000;

It is a chessboard, so I think it would be much better to format it like this:

let centre: u64 = 0b
                  00000000
                  00000000
                  00111100
                  00111100
                  00111100
                  00111100
                  00000000
                  00000000;

However, the above example does not compile, since newlines are interpreted as spaces inside my literal. Is there any way to achieve this?

+4
source share
1 answer

It is impossible to combine tokens into a new token (as you could do with ##in the C preprocessor) with macros in the standard library (like from Rust 1.22).

. 0b_ , . ORs , .

macro_rules! chessboard {
    ($line0:tt $line1:tt $line2:tt $line3:tt $line4:tt $line5:tt $line6:tt $line7:tt) => {
        ($line0 << 56) |
        ($line1 << 48) |
        ($line2 << 40) |
        ($line3 << 32) |
        ($line4 << 24) |
        ($line5 << 16) |
        ($line6 <<  8) |
        ($line7 <<  0)
    }
}

fn main() {
    let centre: u64 = chessboard!(
        0b_00000000
        0b_00000000
        0b_00111100
        0b_00111100
        0b_00111100
        0b_00111100
        0b_00000000
        0b_00000000);
    println!("{:#b}", centre);
}
+5

Source: https://habr.com/ru/post/1690094/


All Articles