如何格式化一个常量字符串

13

我该如何使一个const字符串的一部分根据某个标志条件化?

#[cfg(target_os = "macos")]
const OS: &'static str = "OSx";
#[cfg(target_os = "windows")]
const OS: &'static str = "Windows";

const SOME_STRING: &'static str = format!("this os is {}", OS);

这段代码无法编译,因为format宏返回一个String。我希望能够进行格式化而不进行任何分配。是否可能在不使整个字符串条件化的情况下实现此操作?

2个回答

10
您可以使用 const_format crate 来实现此功能。
use const_format::formatcp;

#[cfg(target_os = "macos")]
const OS: &'static str = "OSx";
#[cfg(target_os = "windows")]
const OS: &'static str = "Windows";

const SOME_STRING: &'static str = formatcp!("this os is {}", OS);

pub fn main() {
    println!("{}", SOME_STRING);
}

this os is Windows

这段代码只是示例,您可以简单地将 "this os is" 复制到每个 cfg 字符串中,并且应该考虑使用 std::env::const::OS


9

2
“const fn” 是否也允许像 “const sqrt_of_two: f64 = (2.0).sqrt()” 这样的操作呢? - Linear
2
可以通过滥用宏来做到这一点……但这很可能不值得。非常不值得。 - DK.
@Jsor: 可能吧。目前还不清楚 Rust 将会有多少编译时函数求值(CTFE)。个人而言,我倾向于“所有自包含的内容”,但我并不是决策者 :) - Matthieu M.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接