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 /// The `print!` macro will lock the standard output on each call. If you call
31 /// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
32 /// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
34 /// use std::io::{stdout, Write};
36 /// let mut lock = stdout().lock();
37 /// write!(lock, "hello world").unwrap();
40 /// Use `print!` only for the primary output of your program. Use
41 /// [`eprint!`] instead to print error and progress messages.
43 /// [flush]: crate::io::Write::flush
44 /// [`println!`]: crate::println
45 /// [`eprint!`]: crate::eprint
46 /// [lock]: crate::io::Stdout
50 /// Panics if writing to `io::stdout()` fails.
55 /// use std::io::{self, Write};
65 /// io::stdout().flush().unwrap();
67 /// print!("this string has a newline, why not choose println! instead?\n");
69 /// io::stdout().flush().unwrap();
72 #[stable(feature = "rust1", since = "1.0.0")]
73 #[cfg_attr(not(test), rustc_diagnostic_item = "print_macro")]
74 #[allow_internal_unstable(print_internals)]
77 $crate::io::_print($crate::format_args!($($arg)*));
81 /// Prints to the standard output, with a newline.
83 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
84 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
86 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
87 /// See [`std::fmt`] for more information.
89 /// The `println!` macro will lock the standard output on each call. If you call
90 /// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
91 /// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
93 /// use std::io::{stdout, Write};
95 /// let mut lock = stdout().lock();
96 /// writeln!(lock, "hello world").unwrap();
99 /// Use `println!` only for the primary output of your program. Use
100 /// [`eprintln!`] instead to print error and progress messages.
102 /// [`std::fmt`]: crate::fmt
103 /// [`eprintln!`]: crate::eprintln
104 /// [lock]: crate::io::Stdout
108 /// Panics if writing to [`io::stdout`] fails.
110 /// [`io::stdout`]: crate::io::stdout
115 /// println!(); // prints just a newline
116 /// println!("hello there!");
117 /// println!("format {} arguments", "some");
118 /// let local_variable = "some";
119 /// println!("format {local_variable} arguments");
122 #[stable(feature = "rust1", since = "1.0.0")]
123 #[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
124 #[allow_internal_unstable(print_internals, format_args_nl)]
125 macro_rules! println {
130 $crate::io::_print($crate::format_args_nl!($($arg)*));
134 /// Prints to the standard error.
136 /// Equivalent to the [`print!`] macro, except that output goes to
137 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
140 /// Use `eprint!` only for error and progress messages. Use `print!`
141 /// instead for the primary output of your program.
143 /// [`io::stderr`]: crate::io::stderr
144 /// [`io::stdout`]: crate::io::stdout
148 /// Panics if writing to `io::stderr` fails.
153 /// eprint!("Error: Could not complete task");
156 #[stable(feature = "eprint", since = "1.19.0")]
157 #[cfg_attr(not(test), rustc_diagnostic_item = "eprint_macro")]
158 #[allow_internal_unstable(print_internals)]
159 macro_rules! eprint {
161 $crate::io::_eprint($crate::format_args!($($arg)*));
165 /// Prints to the standard error, with a newline.
167 /// Equivalent to the [`println!`] macro, except that output goes to
168 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
171 /// Use `eprintln!` only for error and progress messages. Use `println!`
172 /// instead for the primary output of your program.
174 /// [`io::stderr`]: crate::io::stderr
175 /// [`io::stdout`]: crate::io::stdout
176 /// [`println!`]: crate::println
180 /// Panics if writing to `io::stderr` fails.
185 /// eprintln!("Error: Could not complete task");
188 #[stable(feature = "eprint", since = "1.19.0")]
189 #[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
190 #[allow_internal_unstable(print_internals, format_args_nl)]
191 macro_rules! eprintln {
193 $crate::eprint!("\n")
196 $crate::io::_eprint($crate::format_args_nl!($($arg)*));
200 /// Prints and returns the value of a given expression for quick and dirty
207 /// let b = dbg!(a * 2) + 1;
208 /// // ^-- prints: [src/main.rs:2] a * 2 = 4
209 /// assert_eq!(b, 5);
212 /// The macro works by using the `Debug` implementation of the type of
213 /// the given expression to print the value to [stderr] along with the
214 /// source location of the macro invocation as well as the source code
215 /// of the expression.
217 /// Invoking the macro on an expression moves and takes ownership of it
218 /// before returning the evaluated expression unchanged. If the type
219 /// of the expression does not implement `Copy` and you don't want
220 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
221 /// for some expression `expr`.
223 /// The `dbg!` macro works exactly the same in release builds.
224 /// This is useful when debugging issues that only occur in release
225 /// builds or when debugging in release mode is significantly faster.
227 /// Note that the macro is intended as a debugging tool and therefore you
228 /// should avoid having uses of it in version control for long periods
229 /// (other than in tests and similar).
230 /// Debug output from production code is better done with other facilities
231 /// such as the [`debug!`] macro from the [`log`] crate.
235 /// The exact output printed by this macro should not be relied upon
236 /// and is subject to future changes.
240 /// Panics if writing to `io::stderr` fails.
242 /// # Further examples
244 /// With a method call:
247 /// fn foo(n: usize) {
248 /// if let Some(_) = dbg!(n.checked_sub(4)) {
256 /// This prints to [stderr]:
259 /// [src/main.rs:4] n.checked_sub(4) = None
262 /// Naive factorial implementation:
265 /// fn factorial(n: u32) -> u32 {
266 /// if dbg!(n <= 1) {
269 /// dbg!(n * factorial(n - 1))
273 /// dbg!(factorial(4));
276 /// This prints to [stderr]:
279 /// [src/main.rs:3] n <= 1 = false
280 /// [src/main.rs:3] n <= 1 = false
281 /// [src/main.rs:3] n <= 1 = false
282 /// [src/main.rs:3] n <= 1 = true
283 /// [src/main.rs:4] 1 = 1
284 /// [src/main.rs:5] n * factorial(n - 1) = 2
285 /// [src/main.rs:5] n * factorial(n - 1) = 6
286 /// [src/main.rs:5] n * factorial(n - 1) = 24
287 /// [src/main.rs:11] factorial(4) = 24
290 /// The `dbg!(..)` macro moves the input:
293 /// /// A wrapper around `usize` which importantly is not Copyable.
295 /// struct NoCopy(usize);
297 /// let a = NoCopy(42);
298 /// let _ = dbg!(a); // <-- `a` is moved here.
299 /// let _ = dbg!(a); // <-- `a` is moved again; error!
302 /// You can also use `dbg!()` without a value to just print the
303 /// file and line whenever it's reached.
305 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
306 /// a tuple (and return it, too):
309 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
312 /// However, a single argument with a trailing comma will still not be treated
313 /// as a tuple, following the convention of ignoring trailing commas in macro
314 /// invocations. You can use a 1-tuple directly if you need one:
317 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
318 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
321 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
322 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
323 /// [`log`]: https://crates.io/crates/log
325 #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")]
326 #[stable(feature = "dbg_macro", since = "1.32.0")]
328 // NOTE: We cannot use `concat!` to make a static string as a format argument
329 // of `eprintln!` because `file!` could contain a `{` or
330 // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
331 // will be malformed.
333 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!())
335 ($val:expr $(,)?) => {
336 // Use of `match` here is intentional because it affects the lifetimes
337 // of temporaries - https://stackoverflow.com/a/48732525/1063961
340 $crate::eprintln!("[{}:{}] {} = {:#?}",
341 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
346 ($($val:expr),+ $(,)?) => {
347 ($($crate::dbg!($val)),+,)
352 macro_rules! assert_approx_eq {
353 ($a:expr, $b:expr) => {{
354 let (a, b) = (&$a, &$b);
355 assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);