rust - 如何格式化这样的字符串?

标签 rust rustfmt

static TEST: &str = "test: {}";

fn main() {
    let string = format!(TEST, "OK");
    println!("{}", string);
}

我想构造字符串“test: OK”,但这不起作用。我该怎么做?

最佳答案

format! 宏需要在编译时知道实际的格式字符串。这不包括使用变量和 static,但也不包括 const(在编译时知道,但在比宏扩展更晚的编译阶段)。

但是在这种特定情况下,您可以通过使用另一个宏模拟变量来解决您的问题:

macro_rules! test_fmt_str {
    () => {
        "test: {}"
    }
}

fn main() {
    let string = format!(test_fmt_str!(), "OK");
    println!("{}", string);
}

( Permalink to the playground )

如果您的格式字符串在编译时实际上并不知道并且不能在这样的宏中使用,那么您需要 use a dynamic template engine .

关于rust - 如何格式化这样的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406129/

相关文章:

rust - 有没有一种稳定的方法来告诉 Rustfmt 跳过整个文件

rust - Rustfmt 是否可以选择使类型显式化?

rust - 错误 : `line` does not live long enough but it's ok in playground

macros - 当内部宏接受参数时,如何定义一个定义另一个宏的宏?

rust - 使用 tokio 0.1.x 生成具有非静态生命周期的任务

rust - Rust是否会缩小生命周期以满足对其定义的约束?

module - 不能使用 "super"来引用由 "use"从另一个 crate 引入的名称

c++ - 如何在提交时自动格式化 Rust(和 C++)代码?