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 = "../../core/src/macros/panic.md")]
9 #[stable(feature = "rust1", since = "1.0.0")]
10 #[allow_internal_unstable(libstd_sys_internals)]
11 #[cfg_attr(not(any(bootstrap, test)), rustc_diagnostic_item = "std_panic_macro")]
13 () => ({ $crate::panic!("explicit panic") });
14 ($msg:expr $(,)?) => ({ $crate::rt::begin_panic($msg) });
15 ($fmt:expr, $($arg:tt)+) => ({
16 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
20 /// Prints to the standard output.
22 /// Equivalent to the [`println!`] macro except that a newline is not printed at
23 /// the end of the message.
25 /// Note that stdout is frequently line-buffered by default so it may be
26 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
29 /// Use `print!` only for the primary output of your program. Use
30 /// [`eprint!`] instead to print error and progress messages.
32 /// [flush]: crate::io::Write::flush
36 /// Panics if writing to `io::stdout()` fails.
41 /// use std::io::{self, Write};
51 /// io::stdout().flush().unwrap();
53 /// print!("this string has a newline, why not choose println! instead?\n");
55 /// io::stdout().flush().unwrap();
58 #[stable(feature = "rust1", since = "1.0.0")]
59 #[allow_internal_unstable(print_internals)]
61 ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
64 /// Prints to the standard output, with a newline.
66 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
67 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
69 /// Use the [`format!`] syntax to write data to the standard output.
70 /// See [`std::fmt`] for more information.
72 /// Use `println!` only for the primary output of your program. Use
73 /// [`eprintln!`] instead to print error and progress messages.
75 /// [`std::fmt`]: crate::fmt
79 /// Panics if writing to [`io::stdout`] fails.
81 /// [`io::stdout`]: crate::io::stdout
86 /// println!(); // prints just a newline
87 /// println!("hello there!");
88 /// println!("format {} arguments", "some");
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[allow_internal_unstable(print_internals, format_args_nl)]
93 macro_rules! println {
94 () => ($crate::print!("\n"));
96 $crate::io::_print($crate::format_args_nl!($($arg)*));
100 /// Prints to the standard error.
102 /// Equivalent to the [`print!`] macro, except that output goes to
103 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
106 /// Use `eprint!` only for error and progress messages. Use `print!`
107 /// instead for the primary output of your program.
109 /// [`io::stderr`]: crate::io::stderr
110 /// [`io::stdout`]: crate::io::stdout
114 /// Panics if writing to `io::stderr` fails.
119 /// eprint!("Error: Could not complete task");
122 #[stable(feature = "eprint", since = "1.19.0")]
123 #[allow_internal_unstable(print_internals)]
124 macro_rules! eprint {
125 ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
128 /// Prints to the standard error, with a newline.
130 /// Equivalent to the [`println!`] macro, except that output goes to
131 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
134 /// Use `eprintln!` only for error and progress messages. Use `println!`
135 /// instead for the primary output of your program.
137 /// [`io::stderr`]: crate::io::stderr
138 /// [`io::stdout`]: crate::io::stdout
142 /// Panics if writing to `io::stderr` fails.
147 /// eprintln!("Error: Could not complete task");
150 #[stable(feature = "eprint", since = "1.19.0")]
151 #[allow_internal_unstable(print_internals, format_args_nl)]
152 macro_rules! eprintln {
153 () => ($crate::eprint!("\n"));
155 $crate::io::_eprint($crate::format_args_nl!($($arg)*));
159 /// Prints and returns the value of a given expression for quick and dirty
166 /// let b = dbg!(a * 2) + 1;
167 /// // ^-- prints: [src/main.rs:2] a * 2 = 4
168 /// assert_eq!(b, 5);
171 /// The macro works by using the `Debug` implementation of the type of
172 /// the given expression to print the value to [stderr] along with the
173 /// source location of the macro invocation as well as the source code
174 /// of the expression.
176 /// Invoking the macro on an expression moves and takes ownership of it
177 /// before returning the evaluated expression unchanged. If the type
178 /// of the expression does not implement `Copy` and you don't want
179 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
180 /// for some expression `expr`.
182 /// The `dbg!` macro works exactly the same in release builds.
183 /// This is useful when debugging issues that only occur in release
184 /// builds or when debugging in release mode is significantly faster.
186 /// Note that the macro is intended as a debugging tool and therefore you
187 /// should avoid having uses of it in version control for long periods.
188 /// Use cases involving debug output that should be added to version control
189 /// are better served by macros such as [`debug!`] from the [`log`] crate.
193 /// The exact output printed by this macro should not be relied upon
194 /// and is subject to future changes.
198 /// Panics if writing to `io::stderr` fails.
200 /// # Further examples
202 /// With a method call:
205 /// fn foo(n: usize) {
206 /// if let Some(_) = dbg!(n.checked_sub(4)) {
214 /// This prints to [stderr]:
217 /// [src/main.rs:4] n.checked_sub(4) = None
220 /// Naive factorial implementation:
223 /// fn factorial(n: u32) -> u32 {
224 /// if dbg!(n <= 1) {
227 /// dbg!(n * factorial(n - 1))
231 /// dbg!(factorial(4));
234 /// This prints to [stderr]:
237 /// [src/main.rs:3] n <= 1 = false
238 /// [src/main.rs:3] n <= 1 = false
239 /// [src/main.rs:3] n <= 1 = false
240 /// [src/main.rs:3] n <= 1 = true
241 /// [src/main.rs:4] 1 = 1
242 /// [src/main.rs:5] n * factorial(n - 1) = 2
243 /// [src/main.rs:5] n * factorial(n - 1) = 6
244 /// [src/main.rs:5] n * factorial(n - 1) = 24
245 /// [src/main.rs:11] factorial(4) = 24
248 /// The `dbg!(..)` macro moves the input:
251 /// /// A wrapper around `usize` which importantly is not Copyable.
253 /// struct NoCopy(usize);
255 /// let a = NoCopy(42);
256 /// let _ = dbg!(a); // <-- `a` is moved here.
257 /// let _ = dbg!(a); // <-- `a` is moved again; error!
260 /// You can also use `dbg!()` without a value to just print the
261 /// file and line whenever it's reached.
263 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
264 /// a tuple (and return it, too):
267 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
270 /// However, a single argument with a trailing comma will still not be treated
271 /// as a tuple, following the convention of ignoring trailing commas in macro
272 /// invocations. You can use a 1-tuple directly if you need one:
275 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
276 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
279 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
280 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
281 /// [`log`]: https://crates.io/crates/log
283 #[stable(feature = "dbg_macro", since = "1.32.0")]
286 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
288 ($val:expr $(,)?) => {
289 // Use of `match` here is intentional because it affects the lifetimes
290 // of temporaries - https://stackoverflow.com/a/48732525/1063961
293 $crate::eprintln!("[{}:{}] {} = {:#?}",
294 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
299 ($($val:expr),+ $(,)?) => {
300 ($($crate::dbg!($val)),+,)
305 macro_rules! assert_approx_eq {
306 ($a:expr, $b:expr) => {{
307 let (a, b) = (&$a, &$b);
308 assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);