Order execution macro

I use a string interning library ( string-cache ) that uses macros to efficiently create elements ( atom!). However, for simplicity, here is a similar macro showing the problem

macro_rules! string_intern {
   ("d") => ("Found D");
}

Let's say I need to call this macro from another macro and give it a string version of the identifier.

macro_rules! print_ident {
    ($id:ident) => (
        string_intern!(stringify!($id));
    );
}

However calling this macro

fn main() {
    print_ident!(d);
}

Error with error:

error: no rules expected the token `stringify`
 --> <anon>:7:24
  |
7 |         string_intern!(stringify!($id));
  |                        ^^^^^^^^^

Playground

I know that it stringify!correctly converts the identifier dto a string "d", because providing it println!works as expected. Is there a way to pass the identifier that I want to convert to a string in string_intern?

+4
2

println! , format_args! , "", . ; ( ).

, ; . . , , , , .

+9

string_intern! "d" , : stringify, !,... . string_intern!, , :

macro_rules! string_intern {
    ($e:expr) => {
        match $e {
            "d" => "Found D",
            _ => "Not found",
        }
    }
}

, .

0

Source: https://habr.com/ru/post/1656511/


All Articles