7

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.

Jimmy Chu
  • 972
  • 8
  • 27
  • 4
    The macro *is* returning the value, but you're using the macro in a context where a `()` is expected (because `main` returns `()`). Try assigning the result to a variable. – Francis Gagné Jun 04 '19 at 04:04
  • 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! Thanks for your input @FrancisGagné – Jimmy Chu Jun 04 '19 at 04:23

1 Answers1

3

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.

Jimmy Chu
  • 972
  • 8
  • 27