Does the rust format! macro provide for user-specified fill characters

Viewed 372

With Rust I can have a user-specified width in my call to format!,

format!("{:>width$}", result.clone(), width=v as usize )

I can even specify the fill character (like the - below)

format!("{:->width$}", result.clone(), width=v as usize )

Or, with a 0,

format!("{:0>width$}", result.clone(), width=v as usize )

But is there a way to have that user-specified? I've tried the following but it doesn't work,

format!("{:fill$>width$}", result.clone(), fill='0' width=v as usize )

I get the following error,

error: invalid format string: expected `'}'`, found `'>'`
   --> src/sequence/renderer.rs:124:28
    |
124 |                 |v| Ok(format!("{:fill$>width$}", result.clone(), fill='0', width=v as usize ))
    |                                 -      ^ expected `}` in format string
    |                                 |
    |                                 because of this opening brace
    |
    = note: if you intended to print `{`, you can escape it using `{{`

error: could not compile `letter-sequence` due to previous error
warning: build failed, waiting for other jobs to finish...
error: build failed
2 Answers

It's not possible at the moment. By looking at the grammar of format string it's not possible to pass fill parameter as an argument.

format := '{' [ argument ] [ ':' format_spec ] '}'
argument := integer | identifier

format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type
fill := character
align := ''
sign := '+' | '-'
width := count
precision := count | '*'
type := '' | '?' | 'x?' | 'X?' | identifier
count := parameter | integer
parameter := argument '$'

As you can see the fill format specifier is directly mapped to a character token, Where as width can be substituted with identifier $(width -> count -> parameter -> argument $ -> identifier $)

Related