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
7 /// Panics the current thread.
9 /// This allows a program to terminate immediately and provide feedback
10 /// to the caller of the program. `panic!` should be used when a program reaches
11 /// an unrecoverable state.
13 /// This macro is the perfect way to assert conditions in example code and in
14 /// tests. `panic!` is closely tied with the `unwrap` method of both [`Option`]
15 /// and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set
16 /// to None or Err variants.
18 /// This macro is used to inject panic into a Rust thread, causing the thread to
19 /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
20 /// and the single-argument form of the `panic!` macro will be the value which
23 /// [`Result`] enum is often a better solution for recovering from errors than
24 /// using the `panic!` macro. This macro should be used to avoid proceeding using
25 /// incorrect values, such as from external sources. Detailed information about
26 /// error handling is found in the [book].
28 /// The multi-argument form of this macro panics with a string and has the
29 /// [`format!`] syntax for building a string.
31 /// See also the macro [`compile_error!`], for raising errors during compilation.
33 /// [runwrap]: ../std/result/enum.Result.html#method.unwrap
34 /// [`Option`]: ../std/option/enum.Option.html#method.unwrap
35 /// [`Result`]: ../std/result/enum.Result.html
36 /// [`format!`]: ../std/macro.format.html
37 /// [`compile_error!`]: ../std/macro.compile_error.html
38 /// [book]: ../book/ch09-00-error-handling.html
40 /// # Current implementation
42 /// If the main thread panics it will terminate all your threads and end your
43 /// program with code `101`.
48 /// # #![allow(unreachable_code)]
50 /// panic!("this is a terrible mistake!");
51 /// panic!(4); // panic with the value of 4 to be collected elsewhere
52 /// panic!("this is a {} {message}", "fancy", message = "message");
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[allow_internal_unstable(libstd_sys_internals)]
59 $crate::panic!("explicit panic")
62 $crate::rt::begin_panic($msg, &($crate::file!(), $crate::line!(), $crate::column!()))
67 ($fmt:expr, $($arg:tt)+) => ({
68 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+),
69 &($crate::file!(), $crate::line!(), $crate::column!()))
73 /// Prints to the standard output.
75 /// Equivalent to the [`println!`] macro except that a newline is not printed at
76 /// the end of the message.
78 /// Note that stdout is frequently line-buffered by default so it may be
79 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
82 /// Use `print!` only for the primary output of your program. Use
83 /// [`eprint!`] instead to print error and progress messages.
85 /// [`println!`]: ../std/macro.println.html
86 /// [flush]: ../std/io/trait.Write.html#tymethod.flush
87 /// [`eprint!`]: ../std/macro.eprint.html
91 /// Panics if writing to `io::stdout()` fails.
96 /// use std::io::{self, Write};
106 /// io::stdout().flush().unwrap();
108 /// print!("this string has a newline, why not choose println! instead?\n");
110 /// io::stdout().flush().unwrap();
113 #[stable(feature = "rust1", since = "1.0.0")]
114 #[allow_internal_unstable(print_internals)]
116 ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
119 /// Prints to the standard output, with a newline.
121 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
122 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
124 /// Use the [`format!`] syntax to write data to the standard output.
125 /// See [`std::fmt`] for more information.
127 /// Use `println!` only for the primary output of your program. Use
128 /// [`eprintln!`] instead to print error and progress messages.
130 /// [`format!`]: ../std/macro.format.html
131 /// [`std::fmt`]: ../std/fmt/index.html
132 /// [`eprintln!`]: ../std/macro.eprintln.html
135 /// Panics if writing to `io::stdout` fails.
140 /// println!(); // prints just a newline
141 /// println!("hello there!");
142 /// println!("format {} arguments", "some");
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[allow_internal_unstable(print_internals, format_args_nl)]
147 macro_rules! println {
148 () => ($crate::print!("\n"));
150 $crate::io::_print($crate::format_args_nl!($($arg)*));
154 /// Prints to the standard error.
156 /// Equivalent to the [`print!`] macro, except that output goes to
157 /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
160 /// Use `eprint!` only for error and progress messages. Use `print!`
161 /// instead for the primary output of your program.
163 /// [`io::stderr`]: ../std/io/struct.Stderr.html
164 /// [`print!`]: ../std/macro.print.html
168 /// Panics if writing to `io::stderr` fails.
173 /// eprint!("Error: Could not complete task");
176 #[stable(feature = "eprint", since = "1.19.0")]
177 #[allow_internal_unstable(print_internals)]
178 macro_rules! eprint {
179 ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
182 /// Prints to the standard error, with a newline.
184 /// Equivalent to the [`println!`] macro, except that output goes to
185 /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
188 /// Use `eprintln!` only for error and progress messages. Use `println!`
189 /// instead for the primary output of your program.
191 /// [`io::stderr`]: ../std/io/struct.Stderr.html
192 /// [`println!`]: ../std/macro.println.html
196 /// Panics if writing to `io::stderr` fails.
201 /// eprintln!("Error: Could not complete task");
204 #[stable(feature = "eprint", since = "1.19.0")]
205 #[allow_internal_unstable(print_internals, format_args_nl)]
206 macro_rules! eprintln {
207 () => ($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 longer periods.
242 /// Use cases involving debug output that should be added to version control
243 /// are better served by macros such as [`debug!`] from the [`log`] crate.
247 /// The exact output printed by this macro should not be relied upon
248 /// and is subject to future changes.
252 /// Panics if writing to `io::stderr` fails.
254 /// # Further examples
256 /// With a method call:
259 /// fn foo(n: usize) {
260 /// if let Some(_) = dbg!(n.checked_sub(4)) {
268 /// This prints to [stderr]:
271 /// [src/main.rs:4] n.checked_sub(4) = None
274 /// Naive factorial implementation:
277 /// fn factorial(n: u32) -> u32 {
278 /// if dbg!(n <= 1) {
281 /// dbg!(n * factorial(n - 1))
285 /// dbg!(factorial(4));
288 /// This prints to [stderr]:
291 /// [src/main.rs:3] n <= 1 = false
292 /// [src/main.rs:3] n <= 1 = false
293 /// [src/main.rs:3] n <= 1 = false
294 /// [src/main.rs:3] n <= 1 = true
295 /// [src/main.rs:4] 1 = 1
296 /// [src/main.rs:5] n * factorial(n - 1) = 2
297 /// [src/main.rs:5] n * factorial(n - 1) = 6
298 /// [src/main.rs:5] n * factorial(n - 1) = 24
299 /// [src/main.rs:11] factorial(4) = 24
302 /// The `dbg!(..)` macro moves the input:
305 /// /// A wrapper around `usize` which importantly is not Copyable.
307 /// struct NoCopy(usize);
309 /// let a = NoCopy(42);
310 /// let _ = dbg!(a); // <-- `a` is moved here.
311 /// let _ = dbg!(a); // <-- `a` is moved again; error!
314 /// You can also use `dbg!()` without a value to just print the
315 /// file and line whenever it's reached.
317 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
318 /// a tuple (and return it, too):
321 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
324 /// However, a single argument with a trailing comma will still not be treated
325 /// as a tuple, following the convention of ignoring trailing commas in macro
326 /// invocations. You can use a 1-tuple directly if you need one:
329 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
330 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
333 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
334 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
335 /// [`log`]: https://crates.io/crates/log
337 #[stable(feature = "dbg_macro", since = "1.32.0")]
340 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
343 // Use of `match` here is intentional because it affects the lifetimes
344 // of temporaries - https://stackoverflow.com/a/48732525/1063961
347 $crate::eprintln!("[{}:{}] {} = {:#?}",
348 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
353 // Trailing comma with single argument is ignored
354 ($val:expr,) => { $crate::dbg!($val) };
355 ($($val:expr),+ $(,)?) => {
356 ($($crate::dbg!($val)),+,)
361 macro_rules! assert_approx_eq {
362 ($a:expr, $b:expr) => ({
363 let (a, b) = (&$a, &$b);
364 assert!((*a - *b).abs() < 1.0e-6,
365 "{} is not approximately equal to {}", *a, *b);