如何格式化const字符串

时间:2015-08-28 21:13:45

标签: rust

如何以某个标志为条件参与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 个答案:

答案 0 :(得分:4)

嗯,首先,您应该了解http://doc.rust-lang.org/stable/std/env/consts/constant.OS.html

其次,你无法真正这样做。你可以使用lazy_static箱子,但这仍然会给你一个分配。

将来,当const fn稳定时,这应该更容易实现。

答案 1 :(得分:1)

您可以使用 const_format 板条箱来执行此操作。

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