Common Standard Macros

include_str!

The include_str! macro reads a UTF-8 text file at compile time and embeds its contents directly into the compiled binary as a &'static str literal.

Syntax and Path Resolution

const TEXT: &'static str = include_str!("relative/path/to/file.txt");
  1. Relative path resolution: A relative path passed to include_str!("data.sql") is resolved relative to the directory containing the current .rs source file (the same file returned by file!()), not the workspace root or current working directory.
  2. Compile-time UTF-8 validation: If the target file does not exist or contains invalid UTF-8 bytes, compilation fails immediately with a compiler error.
  3. Zero runtime I/O: At runtime, the embedded string lives in the binary's read-only data segment (.rodata), so reading it takes $O(1)$ time with zero filesystem calls or heap allocations.
Compile Time (`rustc`):
  Reads `migrations/001_init.sql` from disk ──> Validates UTF-8 ──> Embeds into binary `.rodata`

Runtime:
  `SQL_MIGRATION` is already a `&'static str` pointer + length in memory!

Embedding Config Templates, SQL Queries, or Help Text

Notice that because content-writing.md exists right in the repository root (or any .rs file exists alongside the current source file), include_str! can embed any adjacent text file directly into a const or local binding:

// Embeds this source file itself (or any relative text/SQL/JSON file) at compile time:
const SELF_SOURCE: &str = include_str!("main.rs");

fn main() {
    let line_count = SELF_SOURCE.lines().count();
    let first_line = SELF_SOURCE.lines().next().unwrap_or("");

    println!("Embedded source has {line_count} lines");
    println!("First line: {first_line}");
}
Embedded source has 10 lines
First line: // Embeds this source file itself (or any relative text/SQL/JSON file) at compile time:

Combining include_str! with env!("OUT_DIR") for Generated Files

When a build.rs script generates a text file inside Cargo's output directory ($OUT_DIR), combine concat! and env!("OUT_DIR") inside include_str!:

// Embeds a file generated by `build.rs` inside `$OUT_DIR`:
// const GENERATED_SCHEMA: &str = include_str!(concat!(env!("OUT_DIR"), "/schema.graphql"));

Cargo automatically tracks every file loaded by include_str! and recompiles the crate whenever that file changes on disk.