Built-in macros in the standard library

Apart from println!, there are other useful macros in the standard library that are implemented using the macro_rules! macro. Knowing about them will help us appreciate the places and situations where using a macro is a cleaner solution, while not sacrificing readability.

Some of these macros are as follows:

  • dbg!: This allows you to print the value of expressions with their values. This macro moves whatever is passed to it, so if you only want to give read access to their types, you need to pass a reference to this macro instead. It's quite handy as a tracing macro for expressions during runtime.
  • compile_error!: This macro can be used to report an error from code at compile time. This is a handy macro to use when you are building your own macro and want to report any syntactic or semantic errors to the user.
  • concat!: This macro can be used to concatenate any number of literals passed to it and returns the concatenated literals as a &'static str.
  • env!: This inspects an environment variable at compile time. In a lot of languages, accessing values from the environment variable is mostly done at runtime. In Rust, by using this macro, you can resolve environment variables at compile time. Note that this method panics when it cannot find the variable that's defined, so a safe version of this is the option_env! macro.
  • eprint! and eprintln!: This is similar to println!, but outputs messages to the standard error stream.
  • include_bytes!: This macro can be used as a quick way to read files as an array of bytes, such as &'static [u8; N]. The file path given to it is resolved relative to the current file in which this macro is invoked.
  • stringify!: This macro is useful if you want to get a literal translation of a type or a token as a string. We'll use this when we write our own procedural macro.

If you want to explore the full set of macros that are available in the standard library, they can be found at https://doc.rust-lang.org/std/#macros.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset