是否可以使用变量作为格式的fill参数!宏? [英] Is it possible to use a variable as the fill argument in the format! macro?

查看:110
本文介绍了是否可以使用变量作为格式的fill参数!宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用format!宏模仿Python的rjustljustcenter函数,但是我只能找到一种解决方案,您可以传入字符串和宽度.如果您要传递填充参数,则无法使用.

I wanted to imitate Python's rjust, ljust, and center functions using the format! macro, but I was only able to work out a solution where you can pass in the string and the width. If you want to pass in the fill-argument it doesn't work.

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

The documentation tells me that it is possible to provide variables to format! and for the width argument it works just fine. When I try to use a variable for fill, the compiler does not recognize the pattern.

宽度作为变量起作用:

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

将填充值提供为变量不起作用:

Providing the fill as a variable does not work:

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 `{{`

如果我提供的是单个字符而不是填充变量,那么它可以正常工作.注意*字符:

If I provide a single character instead of the fill-variable, it works fine. Notice the * character:

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

我希望填充变量版本的功能与硬编码的*字符版本相同.

I expected the fill-variable version to work the same as the hardcoded * character version.

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

A workaround is to subtract the length of the text from the width and then create a String of that length (fill-length) made of fill-characters and concatenate them:

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

推荐答案

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

Unfortunately there is no built-in way to do this.

格式化语法是由早期Rust使用者采用的功能演变而来的.简洁意味着新功能在事实之后很难添加.

The formatting syntax evolved with features that early Rust adopters needed at the time. Its terseness means that new features are very difficult to add after the fact.

这篇关于是否可以使用变量作为格式的fill参数!宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆