如何根据整数格式化带缩进的字符串?

How to format strings with indentation based on an integer?

有没有更好的print/format字符串缩进方法:

let text_to_indent = "Indented text!";
for i in 0..indent {
    print!(" ");
}
println!("{}", text_to_indent);

Rust 是否有更方便的方法来做到这一点?

println!("{:indent$}Indented text!", "", indent=indent);

(Playground)

第一个占位符进行缩进。它将按照参数 ident.

中指定的填充(带空格)打印参数 0(空字符串,""

可以这样打印一个变量:

println!("{:indent$}{}", "", text_to_indent, indent=level);