Rust has certain abstractions called macros that are kind of like hooks in React (except that they don't necessarily have anything to do with state). Essentially, they abstract away other Rust code.
A macro is appended with an exclamation point !
.
The println!
code we use to print to the screen is a macro, as is vec!
. They abstract away other code and allow us to write more simplified, clean code.
fn main() {
let v = vec![1,2,3];
for x in &v {
println!("{}", x);
}
}
Macros can be declared using the macro_rules! {}
syntax. For instance vec!
could be implemented like so (this is taken from the Rust Macros documentation):
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}