Common Standard Macros
include_bytes!
The include_bytes! macro reads a file at compile time as raw binary data and embeds it into the compiled executable as a static reference to a fixed-size byte array: &'static [u8; N] (which coerces to &'static [u8]).
Syntax and Comparison with include_str!
const ASSET: &'static [u8] = include_bytes!("assets/logo.png");
| Macro | Return Type | UTF-8 Check at Compile Time? | Typical Use Cases |
|---|---|---|---|
include_str!("path") |
&'static str |
Yes (fails compilation if not valid UTF-8) | SQL queries, HTML/CSS templates, JSON fixtures, Markdown docs |
include_bytes!("path") |
&'static [u8; N] (coerces to &'static [u8]) |
No (accepts arbitrary binary bytes 0x00..=0xFF) |
Icons/images, fonts, TLS certificates, WebAssembly (.wasm) modules, compressed archives |
Because include_bytes! returns &'static [u8; N] with the exact file length N known at compile time, ASSET.len() is a compile-time constant!
const RAW_BYTES: &[u8] = include_bytes!("main.rs");
fn main() {
println!("Embedded byte count: {} bytes", RAW_BYTES.len());
println!("First 8 bytes (hex): {:02X?}", &RAW_BYTES[..8]);
}
Embedded byte count: 196 bytes
First 8 bytes (hex): [63, 6F, 6E, 73, 74, 20, 52, 41]
Guaranteeing Alignment for Embedded Binary Data (#[repr(C, align(N))])
By default, the byte array returned by include_bytes! has an alignment of 1 byte (align_of::<u8>() == 1). If you embed binary data that must be cast or transmuted to a higher-alignment type (such as &[u32], &[f32], or a compiled SPIR-V shader requiring 4-byte or 16-byte alignment), wrap the embedded array inside a generic #[repr(C, align(...))] wrapper struct:
#[repr(C, align(4))]
struct Aligned4<Bytes: ?Sized>(Bytes);
static ALIGNED_DATA: &Aligned4<[u8]> = &Aligned4(*include_bytes!("main.rs"));
fn main() {
let bytes: &[u8] = &ALIGNED_DATA.0;
let ptr = bytes.as_ptr() as usize;
println!(
"Embedded {} bytes at 0x{:x} (4-byte aligned: {})",
bytes.len(),
ptr,
ptr % 4 == 0
);
}
Embedded 349 bytes at 0x1028dc000 (4-byte aligned: true)