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
8 #[doc = include_str!("../../core/src/macros/panic.md")]
10 #[rustc_builtin_macro(std_panic)]
11 #[stable(feature = "rust1", since = "1.0.0")]
12 #[allow_internal_unstable(edition_panic)]
13 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_macro")]
15 // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
16 // depending on the edition of the caller.
18 /* compiler built-in */
22 /// Prints to the standard output.
24 /// Equivalent to the [`println!`] macro except that a newline is not printed at
25 /// the end of the message.
27 /// Note that stdout is frequently line-buffered by default so it may be
28 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
31 /// The `print!` macro will lock the standard output on each call. If you call
32 /// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
33 /// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
35 /// use std::io::{stdout, Write};
37 /// let mut lock = stdout().lock();
38 /// write!(lock, "hello world").unwrap();
41 /// Use `print!` only for the primary output of your program. Use
42 /// [`eprint!`] instead to print error and progress messages.
44 /// [flush]: crate::io::Write::flush
45 /// [`println!`]: crate::println
46 /// [`eprint!`]: crate::eprint
47 /// [lock]: crate::io::Stdout
51 /// Panics if writing to `io::stdout()` fails.
53 /// Writing to non-blocking stdout can cause an error, which will lead
54 /// this macro to panic.
59 /// use std::io::{self, Write};
69 /// io::stdout().flush().unwrap();
71 /// print!("this string has a newline, why not choose println! instead?\n");
73 /// io::stdout().flush().unwrap();
76 #[stable(feature = "rust1", since = "1.0.0")]
77 #[cfg_attr(not(test), rustc_diagnostic_item = "print_macro")]
78 #[allow_internal_unstable(print_internals)]
81 $crate::io::_print($crate::format_args!($($arg)*));
85 /// Prints to the standard output, with a newline.
87 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
88 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
90 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
91 /// See [`std::fmt`] for more information.
93 /// The `println!` macro will lock the standard output on each call. If you call
94 /// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
95 /// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
97 /// use std::io::{stdout, Write};
99 /// let mut lock = stdout().lock();
100 /// writeln!(lock, "hello world").unwrap();
103 /// Use `println!` only for the primary output of your program. Use
104 /// [`eprintln!`] instead to print error and progress messages.
106 /// [`std::fmt`]: crate::fmt
107 /// [`eprintln!`]: crate::eprintln
108 /// [lock]: crate::io::Stdout
112 /// Panics if writing to [`io::stdout`] fails.
114 /// Writing to non-blocking stdout can cause an error, which will lead
115 /// this macro to panic.
117 /// [`io::stdout`]: crate::io::stdout
122 /// println!(); // prints just a newline
123 /// println!("hello there!");
124 /// println!("format {} arguments", "some");
125 /// let local_variable = "some";
126 /// println!("format {local_variable} arguments");
129 #[stable(feature = "rust1", since = "1.0.0")]
130 #[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
131 #[allow_internal_unstable(print_internals, format_args_nl)]
132 macro_rules! println {
137 $crate::io::_print($crate::format_args_nl!($($arg)*));
141 /// Prints to the standard error.
143 /// Equivalent to the [`print!`] macro, except that output goes to
144 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
147 /// Use `eprint!` only for error and progress messages. Use `print!`
148 /// instead for the primary output of your program.
150 /// [`io::stderr`]: crate::io::stderr
151 /// [`io::stdout`]: crate::io::stdout
155 /// Panics if writing to `io::stderr` fails.
157 /// Writing to non-blocking stdout can cause an error, which will lead
158 /// this macro to panic.
163 /// eprint!("Error: Could not complete task");
166 #[stable(feature = "eprint", since = "1.19.0")]
167 #[cfg_attr(not(test), rustc_diagnostic_item = "eprint_macro")]
168 #[allow_internal_unstable(print_internals)]
169 macro_rules! eprint {
171 $crate::io::_eprint($crate::format_args!($($arg)*));
175 /// Prints to the standard error, with a newline.
177 /// Equivalent to the [`println!`] macro, except that output goes to
178 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
181 /// Use `eprintln!` only for error and progress messages. Use `println!`
182 /// instead for the primary output of your program.
184 /// [`io::stderr`]: crate::io::stderr
185 /// [`io::stdout`]: crate::io::stdout
186 /// [`println!`]: crate::println
190 /// Panics if writing to `io::stderr` fails.
192 /// Writing to non-blocking stdout can cause an error, which will lead
193 /// this macro to panic.
198 /// eprintln!("Error: Could not complete task");
201 #[stable(feature = "eprint", since = "1.19.0")]
202 #[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
203 #[allow_internal_unstable(print_internals, format_args_nl)]
204 macro_rules! eprintln {
206 $crate::eprint!("\n")
209 $crate::io::_eprint($crate::format_args_nl!($($arg)*));
213 /// Prints and returns the value of a given expression for quick and dirty
220 /// let b = dbg!(a * 2) + 1;
221 /// // ^-- prints: [src/main.rs:2] a * 2 = 4
222 /// assert_eq!(b, 5);
225 /// The macro works by using the `Debug` implementation of the type of
226 /// the given expression to print the value to [stderr] along with the
227 /// source location of the macro invocation as well as the source code
228 /// of the expression.
230 /// Invoking the macro on an expression moves and takes ownership of it
231 /// before returning the evaluated expression unchanged. If the type
232 /// of the expression does not implement `Copy` and you don't want
233 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
234 /// for some expression `expr`.
236 /// The `dbg!` macro works exactly the same in release builds.
237 /// This is useful when debugging issues that only occur in release
238 /// builds or when debugging in release mode is significantly faster.
240 /// Note that the macro is intended as a debugging tool and therefore you
241 /// should avoid having uses of it in version control for long periods
242 /// (other than in tests and similar).
243 /// Debug output from production code is better done with other facilities
244 /// such as the [`debug!`] macro from the [`log`] crate.
248 /// The exact output printed by this macro should not be relied upon
249 /// and is subject to future changes.
253 /// Panics if writing to `io::stderr` fails.
255 /// # Further examples
257 /// With a method call:
260 /// fn foo(n: usize) {
261 /// if let Some(_) = dbg!(n.checked_sub(4)) {
269 /// This prints to [stderr]:
272 /// [src/main.rs:4] n.checked_sub(4) = None
275 /// Naive factorial implementation:
278 /// fn factorial(n: u32) -> u32 {
279 /// if dbg!(n <= 1) {
282 /// dbg!(n * factorial(n - 1))
286 /// dbg!(factorial(4));
289 /// This prints to [stderr]:
292 /// [src/main.rs:3] n <= 1 = false
293 /// [src/main.rs:3] n <= 1 = false
294 /// [src/main.rs:3] n <= 1 = false
295 /// [src/main.rs:3] n <= 1 = true
296 /// [src/main.rs:4] 1 = 1
297 /// [src/main.rs:5] n * factorial(n - 1) = 2
298 /// [src/main.rs:5] n * factorial(n - 1) = 6
299 /// [src/main.rs:5] n * factorial(n - 1) = 24
300 /// [src/main.rs:11] factorial(4) = 24
303 /// The `dbg!(..)` macro moves the input:
306 /// /// A wrapper around `usize` which importantly is not Copyable.
308 /// struct NoCopy(usize);
310 /// let a = NoCopy(42);
311 /// let _ = dbg!(a); // <-- `a` is moved here.
312 /// let _ = dbg!(a); // <-- `a` is moved again; error!
315 /// You can also use `dbg!()` without a value to just print the
316 /// file and line whenever it's reached.
318 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
319 /// a tuple (and return it, too):
322 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
325 /// However, a single argument with a trailing comma will still not be treated
326 /// as a tuple, following the convention of ignoring trailing commas in macro
327 /// invocations. You can use a 1-tuple directly if you need one:
330 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
331 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
334 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
335 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
336 /// [`log`]: https://crates.io/crates/log
338 #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")]
339 #[stable(feature = "dbg_macro", since = "1.32.0")]
341 // NOTE: We cannot use `concat!` to make a static string as a format argument
342 // of `eprintln!` because `file!` could contain a `{` or
343 // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
344 // will be malformed.
346 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!())
348 ($val:expr $(,)?) => {
349 // Use of `match` here is intentional because it affects the lifetimes
350 // of temporaries - https://stackoverflow.com/a/48732525/1063961
353 $crate::eprintln!("[{}:{}] {} = {:#?}",
354 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
359 ($($val:expr),+ $(,)?) => {
360 ($($crate::dbg!($val)),+,)
365 macro_rules! assert_approx_eq {
366 ($a:expr, $b:expr) => {{
367 let (a, b) = (&$a, &$b);
368 assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);