我想使用rjust
宏来模仿Python的ljust
,center
和format!
函数,但是我只能找到一种可以传递字符串和宽度的解决方案。如果您要传递填充参数,则该参数不起作用。
该文档告诉我,可以为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
最佳答案
不幸的是,没有内置的方法可以做到这一点。
格式化语法是由早期Rust使用者采用的功能演变而来的。它的简洁意味着新功能是very difficult to add after the fact。
关于rust - 是否可以使用变量作为格式的fill参数!宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62273315/