rust - 如何使 std::format 中的填充填充动态?

标签 rust

创建格式输出并用 n 填充输出你可以在 Rust 中做这样的事情:

fn main() {
    let title = " Title ";
    println!("┌{:─^11}┐", title);
}
这将打印:
┌── Title ──┐
所以 str 在两边用 ^ 填充(通过 - 居中)在 11 个字符的空间内。
我怎样才能使这个宽度动态化?通过一个变量。

最佳答案

所以事实证明这是一个内置功能。 std::format 自带 width选项用后缀表示 $ .

fn main() {
    let title = " Title ";
    println!("┌{:─^width$}┐", title, width = 11);
}
这将打印:
┌── Title ──┐
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5666cd7f274d436e2216e7ecd0320072

关于rust - 如何使 std::format 中的填充填充动态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69067436/

相关文章:

rust - 如何从构建脚本 (build.rs) 访问当前的 cargo profile (build, test, bench, doc, ....)

c++ - 如何在 Rust winapi 编程中使用 COM VARIANT?

rust - 增量构建引用相同数据的数据结构

rust - "no rules expected the token ` < `"将类型作为标识传递给 macro_rules

rust - 包含原始指针的结构可以实现 Send 并且是 FFI 安全的吗?

rust - 涉及关联类型的不满足特征界限

rust - 为什么借用仍然保留在 if let 的 else block 中?

rust - 如何在实现特征时明确指定生命周期?

rust - 参数数量/类型不匹配

rust - 为什么“通过克隆拥有的变量需要静态生命周期”