The std macros you have not met¶
Level: 201 · working knowledge
One line: Past println!, vec! and assert!, std's macro list holds matches!, concat!, stringify!, include_str!, env!, compile_error!, thread_local! and more — and most of them do their work at compile time, which is the reason they are macros at all.
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
What it has to cover¶
- A test and three placeholders:
matches!(value, Some(n) if n > 2)as abool; andtodo!,unimplemented!andunreachable!, whose panic messages on 1.98.0 are not yet implemented, not implemented and internal error: entered unreachable code — which one says "later", which "never", and which "this cannot happen"? - Text made at compile time:
concat!("a", 1, 'b', true)is the&'static str"a1btrue", andstringify!(1 + 2 * x)is"1 + 2 * x"even when noxexists - Files and variables read at build time:
include_str!andinclude_bytes!take a path relative to the current source file and put the contents in the binary;env!("NAME")stops the build with environment variableNAMEnot defined at compile time and a help line pointing tostd::env::var, whileoption_env!givesNone— which is how rustc_without_cargo tells a Cargo build from barerustc - Where am I:
file!(),line!(),column!()— the three thatdbg!prints in its[file:line:column]prefix — andmodule_path!() - Decisions at compile time:
cfg!(test)is aboolin code that is always compiled, unlike#[cfg](What an attribute is);compile_error!fails the build with your message from a#[cfg]-gated item or a catch-all macro rule;cfg_select!, stable since 1.95.0, picks the first true branch - Checks for debug builds:
debug_assert!and its_eq/_neforms expand to the matchingassertmacro insideif cfg!(debug_assertions) { … }, so the condition is still type-checked but not run in a default--releasebuild — and what that means for a side effect written inside one - Writing into something:
write!andwriteln!against aString(fmt::Write) or a file (io::Write), andformat_args!as the allocation-free valueformat!andprintln!are built on —let args = format_args!("{} {}", "x", 5);followed byprintln!("{args}")compiles on 1.98.0; since which release? - Per-thread statics:
thread_local!with aconst { … }initialiser and.with(|c| …)access; and two newer names —assert_matches!is stable since 1.96.0 but not in the prelude, so a bare call is cannot find macro untiluse std::assert_matches;, whilehash_map!andconcat_bytes!are still nightly-only
The trap it exists for¶
env! where the value was meant to be read when the program runs. env!("API_URL") copies the build machine's value into the binary, so setting the variable before starting the program changes nothing — and a CI build without it set fails to compile at all. Run-time configuration is std::env::var.
Where this sits¶
Macros names the day-one macros — println!, format!, vec!, assert!, assert_eq!, panic!, dbg!, todo! — and What dbg! does owns dbg!. This page is the rest of std's list, one bullet per job.
See also¶
- What
dbg!does — the macro built fromfile!,line!andcolumn! - Running a scratch program —
option_env!("CARGO_PKG_NAME")telling Cargo from barerustc - What an attribute is —
#[cfg]deletes,cfg!()chooses unwrapis a TODO you forgot to remove —todo!as the honest placeholder- The format mini-language — what
write!andformat_args!accept - A function,
macro_rules!, or a procedural macro — check this list before writing your own - std's macro index ↗ — every macro, with its stability badge
If you are coming from another language¶
- C.
__FILE__and__LINE__arefile!()andline!();#erroriscompile_error!; anassertcompiled out underNDEBUGisdebug_assert!in a release build — except that the Rust condition must still compile. C checks aprintfformat string only through compiler warnings, and A format string is a program ↗ shows what an unchecked one can do;format_args!refuses a bad one outright. - Python.
__file__and a frame's line number are looked up at run time;file!()andline!()are literals fixed at compile time.assertstatements vanish underpython -O, the same trade asdebug_assert!— though Python removes the expression entirely. - Go.
//go:embedfills astringor[]bytevariable from a file at build time —include_str!andinclude_bytes!.
Po polsku¶
Biblioteka standardowa ma znacznie więcej makr niż println! i vec!, a większość z nich pracuje w czasie kompilacji: concat! i stringify! sklejają napisy, include_str! wczytuje plik do programu, env! odczytuje zmienną środowiskową maszyny, na której trwa budowanie, a compile_error! przerywa kompilację własnym komunikatem. Najczęstsza pomyłka to env! tam, gdzie chodziło o konfigurację w czasie działania — wartość zostaje „zapieczona” w pliku wykonywalnym, a do odczytu przy uruchomieniu służy std::env::var.
Szukaj po polsku: makra biblioteki standardowej · makra czasu kompilacji · rust env vs option_env · rust include_str · rust todo vs unimplemented