Macros! The Next Level of Rust’s Function

Write it once, and it always there when you need it…

In last month’s blog, we talk about writing the first our Rust code, “Hello, world!”, like newbies usually do. Inside that program, we used one Macros to print our “Hello, world!”. Do you wonder how Rust print that statement? Don’t need to be discombobulated!! Let’s discuss it in this Blog.

First, What are Macros in Rust?!

Macros are a way in Rust that can help us write other code. For the Developer community, they knew this method as meta-programming. Meta-programming is very helpful to us when we code a bunch of lines and use it frequently. With that, we can reduce the amount of code we have to write and maintain.

Wait, a minute! What’s the difference with general function?

The general function may help us reduce the amount of code we have to write and maintain if we use it frequently. But on the other hand, when we code the general function, the number and type of parameters the function is had to be declared first. Because of that point, it makes Macros is more special than general functions. Macros haven’t that limitation. For example, when we want to print a statement, we can use do it like:

println!("Hello, world!");

There is another way to use println!:

println!("Hello, {}!", world);

Talk Less, Practice More !!

It will be hard to understand all theories and understanding above without practice. Now let’s do one typical example that we will use in any kind of program.
When we want to declare Vector data with default values, we will write it like this:

let mut vec_data = Vec::new();
vec_data.push(1);
vec_data.push(2);

If every program or function needs to declare Vector data with default values, the way we use above is very inconvenient. The best way to solve it is by using Meta-programming / Macros. We can write a Macro to help us declare Vector data, for example:

#[macro_export]
macro_rules! vec { ($( $x:expr ),* ) => {
{
let mut vec_data = Vec::new();
$(
vec_data.push($x);
)*
vec_data
}
};}

With the macro code above, now we don’t need to push one by one every time we declare Vector data with default values. How we use the macro code above will be like this:

let v: Vec<u32> = vec![1, 2];

If we solve it with a general function, we need to decide the parameter with specific values and types that will limit our input.

Now you should understand the basics of Macros / Meta-programming in Rust.

If you want to explore other cool blogs of technologies, please stay tune on eCloudture Medium !!!

He is passionate about making the world a better place. He wants to solve business and economic with the latest technology.