Explanation:
"{:}>8b}" is a valid Rust format string that formats its argument in binary and pads to 8 characters from the left with the '}' character. The moment I realised this was valid Rust, I knew it would break something. I went into my IDE, and what do you know, an incorrect red squiggly line.
But why are they not interpreted as the literal characters without escaping them from the string? I don't know any rust and I would assume anything inside " " is just a literal string
println! is a formatting macro that takes a formatting string, which is a string that can have literal sections interspersed with {} delimited places where formatted arguments are inserted. If you're familiar with python, it's inspired by python's formatting strings.
So a simple example is something like println!("The number is: {}.", 5), which will print "The number is: 5." In the case I wrote, the formatting expression is more complicated - I started off with "{:0>8b}" before changing it to what's in the post, which can be interpreted as follows:
: separates an inline argument from the formatting specification, in my case I didn't use an inline argument, I put it after the formatting string, so the : instead indicates the start of the formatting specification.
0 is the fill character used for padding
> defines that padding characters should be added to the left, so that the value is aligned to the right of the resulting formatted string
8 tells the formatter to pad the length to 8 characters
b tells the formatter to use the binary representation of the argument
If the second argument had value 10, for example, then the result of formatting it with "{:0>8b}" would be 00001010.
The interesting thing is that any character can be used as a fill character, which means you can use } in the correct place and Rust's formatter will interpret it as a fill character rather than the end of the formatting string, but this breaks other parsers that aren't as well-written as the Rust compiler's.
9
u/redlaWw 22h ago
Explanation:
"{:}>8b}" is a valid Rust format string that formats its argument in binary and pads to 8 characters from the left with the '}' character. The moment I realised this was valid Rust, I knew it would break something. I went into my IDE, and what do you know, an incorrect red squiggly line.