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(__rust_unstable_column, libstd_sys_internals)]
59 panic!("explicit panic")
62 $crate::rt::begin_panic($msg, &(file!(), line!(), __rust_unstable_column!()))
67 ($fmt:expr, $($arg:tt)+) => ({
68 $crate::rt::begin_panic_fmt(&format_args!($fmt, $($arg)+),
69 &(file!(), line!(), __rust_unstable_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(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 () => (print!("\n"));
150 $crate::io::_print(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(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 () => (eprint!("\n"));
209 $crate::io::_eprint(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 eprintln!("[{}:{}]", file!(), line!());
343 // Use of `match` here is intentional because it affects the lifetimes
344 // of temporaries - https://stackoverflow.com/a/48732525/1063961
347 eprintln!("[{}:{}] {} = {:#?}",
348 file!(), line!(), stringify!($val), &tmp);
353 // Trailing comma with single argument is ignored
354 ($val:expr,) => { dbg!($val) };
355 ($($val:expr),+ $(,)?) => {
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);
369 /// Built-in macros to the compiler itself.
371 /// These macros do not have any corresponding definition with a `macro_rules!`
372 /// macro, but are documented here. Their implementations can be found hardcoded
373 /// into libsyntax itself.
377 /// Causes compilation to fail with the given error message when encountered.
379 /// This macro should be used when a crate uses a conditional compilation strategy to provide
380 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
381 /// which emits an error at *runtime*, rather than during compilation.
385 /// Two such examples are macros and `#[cfg]` environments.
387 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
388 /// the compiler would still emit an error, but the error's message would not mention the two
392 /// macro_rules! give_me_foo_or_bar {
396 /// compile_error!("This macro only accepts `foo` or `bar`");
400 /// give_me_foo_or_bar!(neither);
401 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
404 /// Emit compiler error if one of a number of features isn't available.
407 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
408 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.")
411 /// [`panic!`]: ../std/macro.panic.html
412 #[stable(feature = "compile_error_macro", since = "1.20.0")]
413 #[rustc_doc_only_macro]
414 macro_rules! compile_error {
415 ($msg:expr) => ({ /* compiler built-in */ });
416 ($msg:expr,) => ({ /* compiler built-in */ });
419 /// Constructs parameters for the other string-formatting macros.
421 /// This macro functions by taking a formatting string literal containing
422 /// `{}` for each additional argument passed. `format_args!` prepares the
423 /// additional parameters to ensure the output can be interpreted as a string
424 /// and canonicalizes the arguments into a single type. Any value that implements
425 /// the [`Display`] trait can be passed to `format_args!`, as can any
426 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
428 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
429 /// passed to the macros within [`std::fmt`] for performing useful redirection.
430 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
431 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
432 /// heap allocations.
434 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
435 /// in `Debug` and `Display` contexts as seen below. The example also shows
436 /// that `Debug` and `Display` format to the same thing: the interpolated
437 /// format string in `format_args!`.
440 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
441 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
442 /// assert_eq!("1 foo 2", display);
443 /// assert_eq!(display, debug);
446 /// For more information, see the documentation in [`std::fmt`].
448 /// [`Display`]: ../std/fmt/trait.Display.html
449 /// [`Debug`]: ../std/fmt/trait.Debug.html
450 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
451 /// [`std::fmt`]: ../std/fmt/index.html
452 /// [`format!`]: ../std/macro.format.html
453 /// [`write!`]: ../std/macro.write.html
454 /// [`println!`]: ../std/macro.println.html
461 /// let s = fmt::format(format_args!("hello {}", "world"));
462 /// assert_eq!(s, format!("hello {}", "world"));
464 #[stable(feature = "rust1", since = "1.0.0")]
465 #[rustc_doc_only_macro]
466 macro_rules! format_args {
467 ($fmt:expr) => ({ /* compiler built-in */ });
468 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
471 /// Inspects an environment variable at compile time.
473 /// This macro will expand to the value of the named environment variable at
474 /// compile time, yielding an expression of type `&'static str`.
476 /// If the environment variable is not defined, then a compilation error
477 /// will be emitted. To not emit a compile error, use the [`option_env!`]
480 /// [`option_env!`]: ../std/macro.option_env.html
485 /// let path: &'static str = env!("PATH");
486 /// println!("the $PATH variable at the time of compiling was: {}", path);
489 /// You can customize the error message by passing a string as the second
493 /// let doc: &'static str = env!("documentation", "what's that?!");
496 /// If the `documentation` environment variable is not defined, you'll get
497 /// the following error:
500 /// error: what's that?!
502 #[stable(feature = "rust1", since = "1.0.0")]
503 #[rustc_doc_only_macro]
505 ($name:expr) => ({ /* compiler built-in */ });
506 ($name:expr,) => ({ /* compiler built-in */ });
509 /// Optionally inspects an environment variable at compile time.
511 /// If the named environment variable is present at compile time, this will
512 /// expand into an expression of type `Option<&'static str>` whose value is
513 /// `Some` of the value of the environment variable. If the environment
514 /// variable is not present, then this will expand to `None`. See
515 /// [`Option<T>`][option] for more information on this type.
517 /// A compile time error is never emitted when using this macro regardless
518 /// of whether the environment variable is present or not.
520 /// [option]: ../std/option/enum.Option.html
525 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
526 /// println!("the secret key might be: {:?}", key);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 #[rustc_doc_only_macro]
530 macro_rules! option_env {
531 ($name:expr) => ({ /* compiler built-in */ });
532 ($name:expr,) => ({ /* compiler built-in */ });
535 /// Concatenates identifiers into one identifier.
537 /// This macro takes any number of comma-separated identifiers, and
538 /// concatenates them all into one, yielding an expression which is a new
539 /// identifier. Note that hygiene makes it such that this macro cannot
540 /// capture local variables. Also, as a general rule, macros are only
541 /// allowed in item, statement or expression position. That means while
542 /// you may use this macro for referring to existing variables, functions or
543 /// modules etc, you cannot define a new one with it.
548 /// #![feature(concat_idents)]
551 /// fn foobar() -> u32 { 23 }
553 /// let f = concat_idents!(foo, bar);
554 /// println!("{}", f());
556 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
559 #[unstable(feature = "concat_idents_macro", issue = "29599")]
560 #[rustc_doc_only_macro]
561 macro_rules! concat_idents {
562 ($($e:ident),+) => ({ /* compiler built-in */ });
563 ($($e:ident,)+) => ({ /* compiler built-in */ });
566 /// Concatenates literals into a static string slice.
568 /// This macro takes any number of comma-separated literals, yielding an
569 /// expression of type `&'static str` which represents all of the literals
570 /// concatenated left-to-right.
572 /// Integer and floating point literals are stringified in order to be
578 /// let s = concat!("test", 10, 'b', true);
579 /// assert_eq!(s, "test10btrue");
581 #[stable(feature = "rust1", since = "1.0.0")]
582 #[rustc_doc_only_macro]
583 macro_rules! concat {
584 ($($e:expr),*) => ({ /* compiler built-in */ });
585 ($($e:expr,)*) => ({ /* compiler built-in */ });
588 /// Expands to the line number on which it was invoked.
590 /// With [`column!`] and [`file!`], these macros provide debugging information for
591 /// developers about the location within the source.
593 /// The expanded expression has type `u32` and is 1-based, so the first line
594 /// in each file evaluates to 1, the second to 2, etc. This is consistent
595 /// with error messages by common compilers or popular editors.
596 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
597 /// but rather the first macro invocation leading up to the invocation
598 /// of the `line!` macro.
600 /// [`column!`]: macro.column.html
601 /// [`file!`]: macro.file.html
606 /// let current_line = line!();
607 /// println!("defined on line: {}", current_line);
609 #[stable(feature = "rust1", since = "1.0.0")]
610 #[rustc_doc_only_macro]
611 macro_rules! line { () => ({ /* compiler built-in */ }) }
613 /// Expands to the column number at which it was invoked.
615 /// With [`line!`] and [`file!`], these macros provide debugging information for
616 /// developers about the location within the source.
618 /// The expanded expression has type `u32` and is 1-based, so the first column
619 /// in each line evaluates to 1, the second to 2, etc. This is consistent
620 /// with error messages by common compilers or popular editors.
621 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
622 /// but rather the first macro invocation leading up to the invocation
623 /// of the `column!` macro.
625 /// [`line!`]: macro.line.html
626 /// [`file!`]: macro.file.html
631 /// let current_col = column!();
632 /// println!("defined on column: {}", current_col);
634 #[stable(feature = "rust1", since = "1.0.0")]
635 #[rustc_doc_only_macro]
636 macro_rules! column { () => ({ /* compiler built-in */ }) }
638 /// Expands to the file name in which it was invoked.
640 /// With [`line!`] and [`column!`], these macros provide debugging information for
641 /// developers about the location within the source.
644 /// The expanded expression has type `&'static str`, and the returned file
645 /// is not the invocation of the `file!` macro itself, but rather the
646 /// first macro invocation leading up to the invocation of the `file!`
649 /// [`line!`]: macro.line.html
650 /// [`column!`]: macro.column.html
655 /// let this_file = file!();
656 /// println!("defined in file: {}", this_file);
658 #[stable(feature = "rust1", since = "1.0.0")]
659 #[rustc_doc_only_macro]
660 macro_rules! file { () => ({ /* compiler built-in */ }) }
662 /// Stringifies its arguments.
664 /// This macro will yield an expression of type `&'static str` which is the
665 /// stringification of all the tokens passed to the macro. No restrictions
666 /// are placed on the syntax of the macro invocation itself.
668 /// Note that the expanded results of the input tokens may change in the
669 /// future. You should be careful if you rely on the output.
674 /// let one_plus_one = stringify!(1 + 1);
675 /// assert_eq!(one_plus_one, "1 + 1");
677 #[stable(feature = "rust1", since = "1.0.0")]
678 #[rustc_doc_only_macro]
679 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
681 /// Includes a utf8-encoded file as a string.
683 /// The file is located relative to the current file. (similarly to how
684 /// modules are found)
686 /// This macro will yield an expression of type `&'static str` which is the
687 /// contents of the file.
691 /// Assume there are two files in the same directory with the following
694 /// File 'spanish.in':
702 /// ```ignore (cannot-doctest-external-file-dependency)
704 /// let my_str = include_str!("spanish.in");
705 /// assert_eq!(my_str, "adiรณs\n");
706 /// print!("{}", my_str);
710 /// Compiling 'main.rs' and running the resulting binary will print "adiรณs".
711 #[stable(feature = "rust1", since = "1.0.0")]
712 #[rustc_doc_only_macro]
713 macro_rules! include_str {
714 ($file:expr) => ({ /* compiler built-in */ });
715 ($file:expr,) => ({ /* compiler built-in */ });
718 /// Includes a file as a reference to a byte array.
720 /// The file is located relative to the current file. (similarly to how
721 /// modules are found)
723 /// This macro will yield an expression of type `&'static [u8; N]` which is
724 /// the contents of the file.
728 /// Assume there are two files in the same directory with the following
731 /// File 'spanish.in':
739 /// ```ignore (cannot-doctest-external-file-dependency)
741 /// let bytes = include_bytes!("spanish.in");
742 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
743 /// print!("{}", String::from_utf8_lossy(bytes));
747 /// Compiling 'main.rs' and running the resulting binary will print "adiรณs".
748 #[stable(feature = "rust1", since = "1.0.0")]
749 #[rustc_doc_only_macro]
750 macro_rules! include_bytes {
751 ($file:expr) => ({ /* compiler built-in */ });
752 ($file:expr,) => ({ /* compiler built-in */ });
755 /// Expands to a string that represents the current module path.
757 /// The current module path can be thought of as the hierarchy of modules
758 /// leading back up to the crate root. The first component of the path
759 /// returned is the name of the crate currently being compiled.
766 /// assert!(module_path!().ends_with("test"));
772 #[stable(feature = "rust1", since = "1.0.0")]
773 #[rustc_doc_only_macro]
774 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
776 /// Evaluates boolean combinations of configuration flags at compile-time.
778 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
779 /// boolean expression evaluation of configuration flags. This frequently
780 /// leads to less duplicated code.
782 /// The syntax given to this macro is the same syntax as the [`cfg`]
785 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
790 /// let my_directory = if cfg!(windows) {
791 /// "windows-specific-directory"
796 #[stable(feature = "rust1", since = "1.0.0")]
797 #[rustc_doc_only_macro]
798 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
800 /// Parses a file as an expression or an item according to the context.
802 /// The file is located relative to the current file (similarly to how
803 /// modules are found).
805 /// Using this macro is often a bad idea, because if the file is
806 /// parsed as an expression, it is going to be placed in the
807 /// surrounding code unhygienically. This could result in variables
808 /// or functions being different from what the file expected if
809 /// there are variables or functions that have the same name in
810 /// the current file.
814 /// Assume there are two files in the same directory with the following
817 /// File 'monkeys.in':
819 /// ```ignore (only-for-syntax-highlight)
820 /// ['๐', '๐', '๐']
824 /// .collect::<String>()
829 /// ```ignore (cannot-doctest-external-file-dependency)
831 /// let my_string = include!("monkeys.in");
832 /// assert_eq!("๐๐๐๐๐๐", my_string);
833 /// println!("{}", my_string);
837 /// Compiling 'main.rs' and running the resulting binary will print
838 /// "๐๐๐๐๐๐".
839 #[stable(feature = "rust1", since = "1.0.0")]
840 #[rustc_doc_only_macro]
841 macro_rules! include {
842 ($file:expr) => ({ /* compiler built-in */ });
843 ($file:expr,) => ({ /* compiler built-in */ });
846 /// Asserts that a boolean expression is `true` at runtime.
848 /// This will invoke the [`panic!`] macro if the provided expression cannot be
849 /// evaluated to `true` at runtime.
853 /// Assertions are always checked in both debug and release builds, and cannot
854 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
855 /// release builds by default.
857 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
858 /// violated could lead to unsafety.
860 /// Other use-cases of `assert!` include testing and enforcing run-time
861 /// invariants in safe code (whose violation cannot result in unsafety).
863 /// # Custom Messages
865 /// This macro has a second form, where a custom panic message can
866 /// be provided with or without arguments for formatting. See [`std::fmt`]
867 /// for syntax for this form.
869 /// [`panic!`]: macro.panic.html
870 /// [`debug_assert!`]: macro.debug_assert.html
871 /// [`std::fmt`]: ../std/fmt/index.html
876 /// // the panic message for these assertions is the stringified value of the
877 /// // expression given.
880 /// fn some_computation() -> bool { true } // a very simple function
882 /// assert!(some_computation());
884 /// // assert with a custom message
886 /// assert!(x, "x wasn't true!");
888 /// let a = 3; let b = 27;
889 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
891 #[stable(feature = "rust1", since = "1.0.0")]
892 #[rustc_doc_only_macro]
893 macro_rules! assert {
894 ($cond:expr) => ({ /* compiler built-in */ });
895 ($cond:expr,) => ({ /* compiler built-in */ });
896 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });
900 /// Defines `#[cfg]` if-else statements.
902 /// This is similar to the `if/elif` C preprocessor macro by allowing definition
903 /// of a cascade of `#[cfg]` cases, emitting the implementation which matches
906 /// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
907 /// without having to rewrite each clause multiple times.
908 macro_rules! cfg_if {
910 if #[cfg($($meta:meta),*)] { $($it:item)* }
916 $( ( ($($meta),*) ($($it)*) ), )*
922 macro_rules! __cfg_if_items {
923 (($($not:meta,)*) ; ) => {};
924 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
925 __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* }
926 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
930 macro_rules! __cfg_if_apply {
931 ($m:meta, $($it:item)*) => {