Rust Reference ยท Macros
Rust concat!, stringify!, line! and file!
Reference for Rust compile-time text macros: concat!, stringify!, line!, column!, file!, module_path!, with examples of building literals and assertions.
Some macros produce text or numbers while the compiler runs, so the result is a literal baked into your program. concat! joins literals into one &'static str. stringify! turns any tokens into a string. line!, column!, file! and module_path! report where the macro call sits in the source.
They are most useful inside your own macros, for error messages and tests that should name the code they check.
const GREETING: &str = concat!("Hello, ", "world", "!", 1, true); let code = stringify!(a + b * 2);
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
concat!(lit1, lit2, ...) // &'static str stringify!(any tokens) // &'static str line!() // u32 column!() // u32 file!() // &'static str module_path!() // &'static str
| Macro | Result |
|---|---|
concat! |
Joins string, char, integer, float and bool literals. Other expressions (even constants) are rejected. |
stringify! |
The tokens as the compiler prints them; spacing is normalized. |
line!, column! |
1-based line and column of the macro call (the outermost one when nested in another macro). |
file! |
Path of the source file as passed to the compiler. |
module_path! |
The module path, such as main::util (the crate name comes first). |
Usage notes
concat!takes literals only.concat!("a", MY_CONST)is a compile error. For constant strings, use aconstandformat!at run time, or a small macro.stringify!does not evaluate. It sees tokens, sostringify!(1+2)is"1 + 2", not"3". Exact spacing may differ between compiler versions.- Pass
$e:exprintostringify!inside a macro to show the original source, which is how test helpers print the failing expression. - Line and column are those of the call site, not of the macro definition, when used in a macro expansion from another file or place.
- Path text varies.
file!()depends on how the crate is built (a relative path under Cargo, a bare name in single-file builds), so do not assert on its whole value. concat_idents!is unstable, so you cannot build identifiers this way on stable Rust.
Related
macro_rules!,env!andinclude_str!,assert!,format!- Lessons: Declarative macros, Modules