Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

rust - How to create a static string at compile time

I want to create a long &'static str made of repeating sequences of chars, e.g. abcabcabc...

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Including a file

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"));

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));

See also:

The far future

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...