Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from macro_rules! in Rust [duplicate]

Tags:

rust

I am going through Rust by Examples - Macros/DSL

The code shows:

macro_rules! calculate {
    (eval $e:expr) => {{
        {
            let val: usize = $e; // Force types to be integers
            println!("{} = {}", stringify!{$e}, val);
        }
    }};
}

fn main() {
    calculate! {
        eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword!
    }

    calculate! {
        eval (1 + 2) * (3 / 4)
    }
}

Now I want my custom macro calculate to return the calculated value. I tried with the following:

macro_rules! calculate {
  (eval $e:expr) => {{
    let val: usize = $e;
    println!("{} = {}", stringify!{$e}, val);
    val
  }};
}

But it returns me error saying error[E0308]: mismatched types in val, expected type (), found type i32.

How can I modify the above macro to return the calculated value? Thanks.

like image 791
Jimmy Chu Avatar asked Jun 04 '19 04:06

Jimmy Chu


People also ask

Can a macro return a value Rust?

No, macros operate on syntax only.

Is macro_rules a macro?

macro_rules allows users to define syntax extension in a declarative way. We call such extensions "macros by example" or simply "macros". Each macro by example has a name, and one or more rules.

Are macros allowed in Rust?

The most widely used form of macros in Rust is the declarative macro. These are also sometimes referred to as “macros by example,” “ macro_rules! macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust match expression.

How does Rust macro work?

Rust provides a powerful macro system that allows metaprogramming. As you've seen in previous chapters, macros look like functions, except that their name ends with a bang ! , but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program.


1 Answers

I think I know what's wrong with it. In the original src code, it should end each calculate! {...} macro call with a semi-colon.

like image 68
Jimmy Chu Avatar answered Sep 24 '22 11:09

Jimmy Chu