include_str Embeds Text At Compile Time

Embed a text file into the binary with include_str so templates and manifests are available at runtime without filesystem reads.

RustConfig Management

Code

rustsnippet
16 lines
// include_str! embeds text at compile time and yields a &'static str
const MANIFEST: &str = include_str!("../Cargo.toml");

fn main() {
    println!("embedded bytes: {}", MANIFEST.len());

    let name_line = MANIFEST
        .lines()
        .find(|line| line.trim_start().starts_with("name ="))
        .unwrap_or("name = <missing>");
    println!("package {name_line}");

    // include_bytes! 得到 &'static [u8; N],适合非文本资源
    let raw: &[u8] = include_bytes!("../Cargo.toml");
    println!("same length: {}", raw.len() == MANIFEST.len());
}

Inside the snippet

include_str Embeds Text At Compile Time is built around the function main.

Using it

The demo output is labeled (embedded bytes:, package, same length:), so every printed line maps back to its originating operation.

Key statements

.unwrap_or("name = <missing>");

Interactive Tools for This Topic

FAQ

What does include_str Embeds Text At Compile Time print when run?
No setup needed: run the file and look for labeled lines like `embedded bytes:`, `package`, `same length:` in the output.