使用 Rust,我可以在调用 format!
时获得用户指定的宽度,
format!("{:>width$}", result.clone(), width=v as usize )
我什至可以指定填充字符(如下面的 -
)
format!("{:->width$}", result.clone(), width=v as usize )
或者,使用0
,
format!("{:0>width$}", result.clone(), width=v as usize )
但是有没有办法让用户指定呢?我已尝试以下方法,但不起作用,
format!("{:fill$>width$}", result.clone(), fill='0' width=v as usize )
我收到以下错误,
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
最佳答案
目前还不可能。通过查看grammar of format string无法将 fill
参数作为参数传递。
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 '$'
如您所见,fill
格式说明符直接映射到 character token ,其中 width
可以替换为 identifier $
(width
-> count
-> parameter
-> 参数 $
-> 标识符 $
)
关于rust - 是否使用rust 格式!宏提供用户指定的填充字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69173413/