1 //! Standard library macros
3 //! This module contains a set of macros which are exported from the standard
4 //! library. Each macro is available for use when linking against the standard
7 #[doc = include_str!("../../core/src/macros/panic.md")]
9 #[rustc_builtin_macro(std_panic)]
10 #[stable(feature = "rust1", since = "1.0.0")]
11 #[allow_internal_unstable(edition_panic)]
12 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_macro")]
14 // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
15 // depending on the edition of the caller.
17 /* compiler built-in */
21 /// Prints to the standard output.
23 /// Equivalent to the [`println!`] macro except that a newline is not printed at
24 /// the end of the message.
26 /// Note that stdout is frequently line-buffered by default so it may be
27 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
30 /// Use `print!` only for the primary output of your program. Use
31 /// [`eprint!`] instead to print error and progress messages.
33 /// [flush]: crate::io::Write::flush
34 /// [`println!`]: crate::println
35 /// [`eprint!`]: crate::eprint
39 /// Panics if writing to `io::stdout()` fails.
44 /// use std::io::{self, Write};
54 /// io::stdout().flush().unwrap();
56 /// print!("this string has a newline, why not choose println! instead?\n");
58 /// io::stdout().flush().unwrap();
61 #[stable(feature = "rust1", since = "1.0.0")]
62 #[cfg_attr(not(test), rustc_diagnostic_item = "print_macro")]
63 #[allow_internal_unstable(print_internals)]
66 $crate::io::_print($crate::format_args!($($arg)*));
70 /// Prints to the standard output, with a newline.
72 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
73 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
75 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
76 /// See [`std::fmt`] for more information.
78 /// Use `println!` only for the primary output of your program. Use
79 /// [`eprintln!`] instead to print error and progress messages.
81 /// [`std::fmt`]: crate::fmt
82 /// [`eprintln!`]: crate::eprintln
86 /// Panics if writing to [`io::stdout`] fails.
88 /// [`io::stdout`]: crate::io::stdout
93 /// println!(); // prints just a newline
94 /// println!("hello there!");
95 /// println!("format {} arguments", "some");
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
100 #[allow_internal_unstable(print_internals, format_args_nl)]
101 macro_rules! println {
106 $crate::io::_print($crate::format_args_nl!($($arg)*));
110 /// Prints to the standard error.
112 /// Equivalent to the [`print!`] macro, except that output goes to
113 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
116 /// Use `eprint!` only for error and progress messages. Use `print!`
117 /// instead for the primary output of your program.
119 /// [`io::stderr`]: crate::io::stderr
120 /// [`io::stdout`]: crate::io::stdout
124 /// Panics if writing to `io::stderr` fails.
129 /// eprint!("Error: Could not complete task");
132 #[stable(feature = "eprint", since = "1.19.0")]
133 #[cfg_attr(not(test), rustc_diagnostic_item = "eprint_macro")]
134 #[allow_internal_unstable(print_internals)]
135 macro_rules! eprint {
137 $crate::io::_eprint($crate::format_args!($($arg)*));
141 /// Prints to the standard error, with a newline.
143 /// Equivalent to the [`println!`] macro, except that output goes to
144 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
147 /// Use `eprintln!` only for error and progress messages. Use `println!`
148 /// instead for the primary output of your program.
150 /// [`io::stderr`]: crate::io::stderr
151 /// [`io::stdout`]: crate::io::stdout
152 /// [`println!`]: crate::println
156 /// Panics if writing to `io::stderr` fails.
161 /// eprintln!("Error: Could not complete task");
164 #[stable(feature = "eprint", since = "1.19.0")]
165 #[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
166 #[allow_internal_unstable(print_internals, format_args_nl)]
167 macro_rules! eprintln {
169 $crate::eprint!("\n")
172 $crate::io::_eprint($crate::format_args_nl!($($arg)*));
176 /// Prints and returns the value of a given expression for quick and dirty
183 /// let b = dbg!(a * 2) + 1;
184 /// // ^-- prints: [src/main.rs:2] a * 2 = 4
185 /// assert_eq!(b, 5);
188 /// The macro works by using the `Debug` implementation of the type of
189 /// the given expression to print the value to [stderr] along with the
190 /// source location of the macro invocation as well as the source code
191 /// of the expression.
193 /// Invoking the macro on an expression moves and takes ownership of it
194 /// before returning the evaluated expression unchanged. If the type
195 /// of the expression does not implement `Copy` and you don't want
196 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
197 /// for some expression `expr`.
199 /// The `dbg!` macro works exactly the same in release builds.
200 /// This is useful when debugging issues that only occur in release
201 /// builds or when debugging in release mode is significantly faster.
203 /// Note that the macro is intended as a debugging tool and therefore you
204 /// should avoid having uses of it in version control for long periods
205 /// (other than in tests and similar).
206 /// Debug output from production code is better done with other facilities
207 /// such as the [`debug!`] macro from the [`log`] crate.
211 /// The exact output printed by this macro should not be relied upon
212 /// and is subject to future changes.
216 /// Panics if writing to `io::stderr` fails.
218 /// # Further examples
220 /// With a method call:
223 /// fn foo(n: usize) {
224 /// if let Some(_) = dbg!(n.checked_sub(4)) {
232 /// This prints to [stderr]:
235 /// [src/main.rs:4] n.checked_sub(4) = None
238 /// Naive factorial implementation:
241 /// fn factorial(n: u32) -> u32 {
242 /// if dbg!(n <= 1) {
245 /// dbg!(n * factorial(n - 1))
249 /// dbg!(factorial(4));
252 /// This prints to [stderr]:
255 /// [src/main.rs:3] n <= 1 = false
256 /// [src/main.rs:3] n <= 1 = false
257 /// [src/main.rs:3] n <= 1 = false
258 /// [src/main.rs:3] n <= 1 = true
259 /// [src/main.rs:4] 1 = 1
260 /// [src/main.rs:5] n * factorial(n - 1) = 2
261 /// [src/main.rs:5] n * factorial(n - 1) = 6
262 /// [src/main.rs:5] n * factorial(n - 1) = 24
263 /// [src/main.rs:11] factorial(4) = 24
266 /// The `dbg!(..)` macro moves the input:
269 /// /// A wrapper around `usize` which importantly is not Copyable.
271 /// struct NoCopy(usize);
273 /// let a = NoCopy(42);
274 /// let _ = dbg!(a); // <-- `a` is moved here.
275 /// let _ = dbg!(a); // <-- `a` is moved again; error!
278 /// You can also use `dbg!()` without a value to just print the
279 /// file and line whenever it's reached.
281 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
282 /// a tuple (and return it, too):
285 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
288 /// However, a single argument with a trailing comma will still not be treated
289 /// as a tuple, following the convention of ignoring trailing commas in macro
290 /// invocations. You can use a 1-tuple directly if you need one:
293 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
294 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
297 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
298 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
299 /// [`log`]: https://crates.io/crates/log
301 #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")]
302 #[stable(feature = "dbg_macro", since = "1.32.0")]
304 // NOTE: We cannot use `concat!` to make a static string as a format argument
305 // of `eprintln!` because `file!` could contain a `{` or
306 // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
307 // will be malformed.
309 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!())
311 ($val:expr $(,)?) => {
312 // Use of `match` here is intentional because it affects the lifetimes
313 // of temporaries - https://stackoverflow.com/a/48732525/1063961
316 $crate::eprintln!("[{}:{}] {} = {:#?}",
317 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
322 ($($val:expr),+ $(,)?) => {
323 ($($crate::dbg!($val)),+,)
328 macro_rules! assert_approx_eq {
329 ($a:expr, $b:expr) => {{
330 let (a, b) = (&$a, &$b);
331 assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);