Noob: Formatting strings with different arguments' types


#1

Hi, guys.
I was playing with “Rust by Example”, Formatting part (click to see). And I found out that I can’t do like that:

write!(f, "RGB ({0}, {1}, {2}) 0x{0:02X}{1:02X}{2:02X}", red, green, blue)

I mean, i can’t use same argument with both { } and {:X}, because it’s throws me

error: argument redeclared with type X when it was previously ``

So, is there any solution other than writing red, green, blue, red, green, blue?


#2

That’s interesting, I hadn’t realized there was that restrictions. It appears if you must display an argument the same way each time so if you did:

write!(f, "RGB ({0:02X}, {1:02X}, {2:02X}) 0x{0:02X}{1:02X}{2:02X}", red, green, blue)

It works fine. you can’t even display a value as 02x and 02X, since those are different. I suspect what is happening is that the write! macro is creating std::fmt::Arguments objects for red green blue and those Argument objects hold the information on how to display the element. Therefor it can’t display it differently at different locations in the string.


#3

Yeah, seems you’re right, but I guess there should be some working decisions…