rust - 是否使用rust 格式!宏提供用户指定的填充字符

标签 rust macros format

使用 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/

相关文章:

c - 在 C 中使用宏删除(或有条件地附加)const 修饰符

macros - 如何在 julia 中创建多行宏?

c - 格式化字符串漏洞 - printf

Python打印方式: with 'format' or percent form?

PHP - 为移动 View 使用预格式化的 html

serialization - 如何在二进制编码文件中的不同记录之间添加分隔符?

rust - 我如何在这里返回&str?

struct - 是否有用于构造包含对临时对象的引用的结构的单行语法?

rust - 为什么将Rust的.expect()称为Expect?

c - 将宏函数定义为(0)是什么意思?