是否可以将变量用作格式的填充参数!宏?

时间:2019-06-19 11:07:44

标签: rust formatting fill

我想使用rjust宏来模仿Pythons ljustcenterformat!函数,但是我只能找到一个可以通过的解决方案在字符串和宽度。如果您要传递填充参数,则无法使用。

文档告诉我可以为format!提供变量,对于width参数,它可以正常工作。当我尝试使用变量进行填充时,编译器无法识别该模式。

宽度作为变量起作用:

fn rjust(text: &str, width: usize, fill: Option<char>) -> String {
    format!("{text:>width$}", text = text, width = width)
}
println!("{}", rjust("Hello", 10)); // "     Hello"

将填充内容设置为变量不起作用:

fn rjust(text: &str, width: usize, fill: char) -> String {
    format!(
        "{text:fill>width$}",
        text = text,
        fill = fill,
        width = width
    )
}
println!("{}", rjust("Hello", 20, '*'));

错误消息:

error: invalid format string: expected `'}'`, found `'>'`
 --> src/lib.rs:4:24
  |
4 |             "{text:fill>width$}",
  |              -         ^ expected `}` in format string
  |              |
  |              because of this opening brace
  |
  = note: if you intended to print `{`, you can escape it using `{{`

如果我只提供一个字符而不是填充变量,则可以正常工作。注意*字符:

fn rjust(text: &str, width: usize, fill: char) -> String {
    format!("{text:*>width$}", text = text, width = width)
}
println!("{}", rjust("Hello", 20, '_')); // ***************Hello

我希望填充变量版本的工作方式与硬编码的*字符版本相同。

一种解决方法是从宽度中减去文本的长度,然后创建由填充字符组成的String长度(填充长度)并将其连接起来:

fn rjust(text: &str, width: usize, fill: char) -> String {
    let fill_len = width - text.len();
    let fill_str: String = (0..fill_len).map(|_| fill).collect();
    String::from(fill_str + text)
}
println!("{}", rjust("Hello", 20, '*')); // ***************Hello

1 个答案:

答案 0 :(得分:2)

不幸的是,没有内置的方法可以做到这一点。

格式化语法是由早期Rust使用者采用的功能演变而来的。简洁意味着very difficult to add after the fact是新功能。