O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dissecting println!

Let's start by diving into the deep end: we'll take our old friend println! apart. Here is its definition from the standard library, without the actual code body:

macro_rules! println {     ($fmt:expr) => (print!(concat!($fmt, "\n")));     ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*)); } 

macro_rules! creates new macros. Its first parameter is the name of the new macro and then it follows the pattern-matched code bodies. Things that start with $ (such as $fmt:expr in the preceding definition) get assigned whatever free-form string is in its place, and everything else (such as the comma in the preceding definition) is parsed verbatim. In the case of println, there are two matches:

  • ($fmt:expr) matches a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required