首页 > 解决方案 > 不锈格式!宏提供用户指定的填充字符

问题描述

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

标签: rustmacrosformat

解决方案


目前是不可能的。通过查看格式字符串的语法,不可能将fill参数作为参数传递。

格式 := '{' [ 参数 ] [ ':' format_spec ] '}'
参数 := 整数 | 标识符

format_spec := [ [fill] align][sign]['#']['0'] [width] ['.' 精度]类型
填充:=字符
对齐:=''
符号 := '+' | '-'
宽度:=计数
精度:=计数| '*'
类型 := '' | “?” | 'X?' | 'X?' | 标识符
计数 := 参数| 整数
参数 := 参数 '$'

如您所见,fill格式说明符直接映射到字符标记,其中 aswidth可以替换为identifier $( width-> count-> parameter-> argument $-> identifier $)


推荐阅读