如何使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);
Run Code Online (Sandbox Code Playgroud)
此代码无法编译,因为format宏返回了String. 我希望能够在没有任何分配的情况下进行这种格式化。是否可以不将整个字符串设为条件?
Min*_*uel 10
您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
this os is Windows
Run Code Online (Sandbox Code Playgroud)
(此代码只是示例,因为您可以简单地复制"this os is"到每个 cfg 字符串中,并且还应该考虑使用std::env::const::OS)
嗯,首先,你应该知道http://doc.rust-lang.org/stable/std/env/consts/constant.OS.html
其次,你不能真正做到这一点。您可以使用lazy_static板条箱,但这最终仍会给您分配。
将来,当const fn稳定时,这应该更容易做到。