如何在编译时创建静态字符串 [英] How to create a static string at compile time
问题描述
我想创建一个由重复字符序列组成的长 &'static str
,例如abcabcabc...
I want to create a long &'static str
made of repeating sequences of chars, e.g. abcabcabc...
在 Rust 中有没有办法通过表达式来做到这一点,例如像 Python 中的 long_str = 1000 * "abc"
之类的东西,还是我必须在 Python 中生成它并将其复制/粘贴到 Rust 代码中?
Is there a way in Rust to do this via an expression, e.g. something like long_str = 1000 * "abc"
in Python, or do I have to generate it in Python and copy/paste it in the Rust code?
推荐答案
你不能在稳定的 Rust 中做这样的事情.您的 1000 * abc"
示例不在编译时"运行;在 Python 中,据我了解 Python.
You cannot do such a thing in stable Rust. Your example of 1000 * "abc"
is not run at "compile time" in Python either, as far as I understand Python.
如果必须是静态的,您可以使用 货物构建脚本.这是一些 Rust 代码,可以在实际编译代码之前做很多事情.具体来说,您可以编写一个包含字符串的源文件,然后使用 include_str!
将其放入您的板条箱:
If it has to be static, you could use a Cargo build script. This is a bit of Rust code that can do lots of things before your code is actually compiled. Specifically, you could write a source file out that has your string and then use include_str!
to bring it into your crate:
build.rs
use std::{
env, error::Error, fs::File, io::{BufWriter, Write}, path::Path,
};
fn main() -> Result<(), Box<Error>> {
let out_dir = env::var("OUT_DIR")?;
let dest_path = Path::new(&out_dir).join("long_string.txt");
let mut f = BufWriter::new(File::create(&dest_path)?);
let long_string = "abc".repeat(100);
write!(f, "{}", long_string)?;
Ok(())
}
lib.rs
static LONG_STRING: &'static str = include_str!(concat!(env!("OUT_DIR"), "/long_string.txt"));
延迟初始化
您可以创建一个 once_cell 或 lazy_static 将在运行时创建字符串的值,但只能创建一次.
Lazy initialization
You could create a once_cell or lazy_static value that would create your string at runtime, but only once.
use once_cell::sync::Lazy; // 1.5.2
static LONG_STR: Lazy<String> = Lazy::new(|| "abc".repeat(5000));
另见:
在某些时候,RFC 911 将全面实施.再加上一些额外的 RFC,每一个都增加了新的功能,将使您能够编写如下内容:
At some point, RFC 911 will be fully implemented. This, plus a handful of additional RFCs, each adding new functionality, will allow you to be able to write something like:
// Does not work yet!
static LONG_STR: String = "abc".repeat(1000);
这篇关于如何在编译时创建静态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!