Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for Rust macros to act as text substitutions like in C?

In C, if you wanted to, you could:

#define    do     {
#define    end    }

// ...

if (foo == bar) do
    foo += 5;
    bar /= foo;
end

Is there a way to do something like this in Rust?

like image 479
Rares Dima Avatar asked Sep 15 '25 03:09

Rares Dima


2 Answers

No (thankfully). Rust macros must always expand to a complete AST node.

If you need textual substitution, use a tool suited for that job such as sed, awk, m4, the C preprocessor, etc. That can likely be driven by a build script.

like image 197
Shepmaster Avatar answered Sep 17 '25 18:09

Shepmaster


There is a toy project that does this, in fact: slag. I have never tried it, though.

It comes with this helpful advice:

Should I use this?

No. Use the default rust syntax.

like image 31
adw Avatar answered Sep 17 '25 20:09

adw