Why struct field as macro argument fails to compile?

Could anyone help explaining why the following would fail with error:

error: no rules expected the token .
--> src/main.rs:12:9
|
1 | macro_rules! foo {
| ---------------- when calling this macro
...
12 | foo!(baz.a);
| ^ no rules expected this token in macro call

macro_rules! foo {
    ($bar:ident) => {{
    }};
}

struct Baz {
    a: f64
}

fn main() {
    let baz = Baz{a:1.0};
    foo!(baz.a);
}

The code work if the main function is changed to:

fn main() {
    let baz = Baz{a:1.0};
    let a = baz.a;
    foo!(a);
}

Is there a way to directly pass struct field as macro argument? E.g., write baz.a in foo!(baz.a).

ident means exactly one identifier, i.e. one word, alphanumeric name, no dots or anything else. But you have .a there which is not an ident. You can use expr instead, which allows any expression, including ones that are more than one word.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.