Rust Reference ยท Macros
Rust env!, option_env! and include_str!
Reference for Rust compile-time data macros: env!, option_env!, include_str!, include_bytes! and include!, with path rules and common build-time uses.
These macros pull data into the program while it is being compiled. env!("NAME") reads an environment variable at compile time and fails the build if it is missing. option_env!("NAME") returns an Option<&'static str> instead. include_str!("file") and include_bytes!("file") embed a file's contents in the binary, and include!("file") pastes Rust source.
The values are fixed once the program is built; changing the environment variable afterwards has no effect. For run-time lookups use std::env::var.
const VERSION: &str = env!("CARGO_PKG_VERSION"); const TEXT: &str = include_str!("notes.txt");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
env!("NAME") // &'static str, compile error if unset env!("NAME", "custom error text") // same, with your own message option_env!("NAME") // Option<&'static str> include_str!("path") // &'static str include_bytes!("path") // &'static [u8; N] include!("path.rs") // parses the file as Rust
| Name | Description |
|---|---|
"NAME" |
A string literal naming an environment variable of the compiler process. |
"path" |
A literal path relative to the file containing the macro call. |
Errors: a missing variable (env!), a missing or unreadable file, or a file that is not valid UTF-8 (include_str!) is a compile-time error, not a panic.
Usage notes
- Cargo sets many variables:
CARGO_PKG_NAME,CARGO_PKG_VERSION,CARGO_MANIFEST_DIRand others are available toenv!under cargo. Plainrustcruns, like our runner, set none of them. - Build scripts can pass values with
cargo:rustc-env=NAME=value, which is a common way to embed a git hash. - Paths are relative to the source file, unlike
std::fs, which is relative to the current directory at run time. - Embedded files grow the binary and need a rebuild to change. That is the point: no file to ship or lose.
- Strings only.
env!returns text; parse numbers yourself, for example with aconsthelper or at start-up. - Non-UTF-8 values are an error for both
env!andoption_env!.