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.
Code
// 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.