1 //! Standard library macros
3 //! This modules 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 = "../libcore/macros/panic.md")]
10 #[stable(feature = "rust1", since = "1.0.0")]
11 #[allow_internal_unstable(libstd_sys_internals)]
14 $crate::panic!("explicit panic")
17 $crate::rt::begin_panic($msg, &($crate::file!(), $crate::line!(), $crate::column!()))
22 ($fmt:expr, $($arg:tt)+) => ({
23 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
27 #[cfg(not(bootstrap))]
28 #[doc(include = "../libcore/macros/panic.md")]
30 #[stable(feature = "rust1", since = "1.0.0")]
31 #[allow_internal_unstable(libstd_sys_internals)]
33 () => ({ $crate::panic!("explicit panic") });
34 ($msg:expr) => ({ $crate::rt::begin_panic($msg) });
35 ($msg:expr,) => ({ $crate::panic!($msg) });
36 ($fmt:expr, $($arg:tt)+) => ({
37 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
41 /// Prints to the standard output.
43 /// Equivalent to the [`println!`] macro except that a newline is not printed at
44 /// the end of the message.
46 /// Note that stdout is frequently line-buffered by default so it may be
47 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
50 /// Use `print!` only for the primary output of your program. Use
51 /// [`eprint!`] instead to print error and progress messages.
53 /// [`println!`]: ../std/macro.println.html
54 /// [flush]: ../std/io/trait.Write.html#tymethod.flush
55 /// [`eprint!`]: ../std/macro.eprint.html
59 /// Panics if writing to `io::stdout()` fails.
64 /// use std::io::{self, Write};
74 /// io::stdout().flush().unwrap();
76 /// print!("this string has a newline, why not choose println! instead?\n");
78 /// io::stdout().flush().unwrap();
81 #[stable(feature = "rust1", since = "1.0.0")]
82 #[allow_internal_unstable(print_internals)]
84 ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
87 /// Prints to the standard output, with a newline.
89 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
90 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
92 /// Use the [`format!`] syntax to write data to the standard output.
93 /// See [`std::fmt`] for more information.
95 /// Use `println!` only for the primary output of your program. Use
96 /// [`eprintln!`] instead to print error and progress messages.
98 /// [`format!`]: ../std/macro.format.html
99 /// [`std::fmt`]: ../std/fmt/index.html
100 /// [`eprintln!`]: ../std/macro.eprintln.html
103 /// Panics if writing to `io::stdout` fails.
108 /// println!(); // prints just a newline
109 /// println!("hello there!");
110 /// println!("format {} arguments", "some");
113 #[stable(feature = "rust1", since = "1.0.0")]
114 #[allow_internal_unstable(print_internals, format_args_nl)]
115 macro_rules! println {
116 () => ($crate::print!("\n"));
118 $crate::io::_print($crate::format_args_nl!($($arg)*));
122 /// Prints to the standard error.
124 /// Equivalent to the [`print!`] macro, except that output goes to
125 /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
128 /// Use `eprint!` only for error and progress messages. Use `print!`
129 /// instead for the primary output of your program.
131 /// [`io::stderr`]: ../std/io/struct.Stderr.html
132 /// [`print!`]: ../std/macro.print.html
136 /// Panics if writing to `io::stderr` fails.
141 /// eprint!("Error: Could not complete task");
144 #[stable(feature = "eprint", since = "1.19.0")]
145 #[allow_internal_unstable(print_internals)]
146 macro_rules! eprint {
147 ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
150 /// Prints to the standard error, with a newline.
152 /// Equivalent to the [`println!`] macro, except that output goes to
153 /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
156 /// Use `eprintln!` only for error and progress messages. Use `println!`
157 /// instead for the primary output of your program.
159 /// [`io::stderr`]: ../std/io/struct.Stderr.html
160 /// [`println!`]: ../std/macro.println.html
164 /// Panics if writing to `io::stderr` fails.
169 /// eprintln!("Error: Could not complete task");
172 #[stable(feature = "eprint", since = "1.19.0")]
173 #[allow_internal_unstable(print_internals, format_args_nl)]
174 macro_rules! eprintln {
175 () => ($crate::eprint!("\n"));
177 $crate::io::_eprint($crate::format_args_nl!($($arg)*));
181 /// Prints and returns the value of a given expression for quick and dirty
188 /// let b = dbg!(a * 2) + 1;
189 /// // ^-- prints: [src/main.rs:2] a * 2 = 4
190 /// assert_eq!(b, 5);
193 /// The macro works by using the `Debug` implementation of the type of
194 /// the given expression to print the value to [stderr] along with the
195 /// source location of the macro invocation as well as the source code
196 /// of the expression.
198 /// Invoking the macro on an expression moves and takes ownership of it
199 /// before returning the evaluated expression unchanged. If the type
200 /// of the expression does not implement `Copy` and you don't want
201 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
202 /// for some expression `expr`.
204 /// The `dbg!` macro works exactly the same in release builds.
205 /// This is useful when debugging issues that only occur in release
206 /// builds or when debugging in release mode is significantly faster.
208 /// Note that the macro is intended as a debugging tool and therefore you
209 /// should avoid having uses of it in version control for longer periods.
210 /// Use cases involving debug output that should be added to version control
211 /// are better served by macros such as [`debug!`] from the [`log`] crate.
215 /// The exact output printed by this macro should not be relied upon
216 /// and is subject to future changes.
220 /// Panics if writing to `io::stderr` fails.
222 /// # Further examples
224 /// With a method call:
227 /// fn foo(n: usize) {
228 /// if let Some(_) = dbg!(n.checked_sub(4)) {
236 /// This prints to [stderr]:
239 /// [src/main.rs:4] n.checked_sub(4) = None
242 /// Naive factorial implementation:
245 /// fn factorial(n: u32) -> u32 {
246 /// if dbg!(n <= 1) {
249 /// dbg!(n * factorial(n - 1))
253 /// dbg!(factorial(4));
256 /// This prints to [stderr]:
259 /// [src/main.rs:3] n <= 1 = false
260 /// [src/main.rs:3] n <= 1 = false
261 /// [src/main.rs:3] n <= 1 = false
262 /// [src/main.rs:3] n <= 1 = true
263 /// [src/main.rs:4] 1 = 1
264 /// [src/main.rs:5] n * factorial(n - 1) = 2
265 /// [src/main.rs:5] n * factorial(n - 1) = 6
266 /// [src/main.rs:5] n * factorial(n - 1) = 24
267 /// [src/main.rs:11] factorial(4) = 24
270 /// The `dbg!(..)` macro moves the input:
273 /// /// A wrapper around `usize` which importantly is not Copyable.
275 /// struct NoCopy(usize);
277 /// let a = NoCopy(42);
278 /// let _ = dbg!(a); // <-- `a` is moved here.
279 /// let _ = dbg!(a); // <-- `a` is moved again; error!
282 /// You can also use `dbg!()` without a value to just print the
283 /// file and line whenever it's reached.
285 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
286 /// a tuple (and return it, too):
289 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
292 /// However, a single argument with a trailing comma will still not be treated
293 /// as a tuple, following the convention of ignoring trailing commas in macro
294 /// invocations. You can use a 1-tuple directly if you need one:
297 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
298 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
301 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
302 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
303 /// [`log`]: https://crates.io/crates/log
305 #[stable(feature = "dbg_macro", since = "1.32.0")]
308 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
311 // Use of `match` here is intentional because it affects the lifetimes
312 // of temporaries - https://stackoverflow.com/a/48732525/1063961
315 $crate::eprintln!("[{}:{}] {} = {:#?}",
316 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
321 // Trailing comma with single argument is ignored
322 ($val:expr,) => { $crate::dbg!($val) };
323 ($($val:expr),+ $(,)?) => {
324 ($($crate::dbg!($val)),+,)
329 macro_rules! assert_approx_eq {
330 ($a:expr, $b:expr) => {{
331 let (a, b) = (&$a, &$b);
332 assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);