Macros in Rust. macro_rules

I postponed this day for a long time, but it was impossible to postpone forever. Well, the time has come. It's time to finally get to grips with macros in Rust. Well, or at least start.





Let's immediately define why you want to use them. Macros are about metaprogramming and, one might even say, partly about reflective programming. Of course, I am not a developer of patterns and standards, but using a macro (declared by macro_rules!) As a replacement for a function is, in my opinion, a bad idea. Firstly, because a function accepts variables of a specific type, and the macro that accepts a variable does not corny knows its type, therefore, the meaning of the operations can be understood only by the name and by the signature of the macro itself. And the syntax of macros is not that very obvious ...





But hopefully this article will make it clearer for you.





What kind of beast is this macro_rules !?

. macro_rules! - , . - , , unwrap. , , , .





, .





:





macro_rules! uncover{







    ($var:ident) => {







        match $var{







            Some(t) => t,







            None => panic!("None value")







        }







    }







}







fn main(){







    let x = Some(2i32);







    let unwrapped = uncover!(x);







    println!("{}", unwrapped);







}







-… . ? -, uncover: 





macro_rules! uncover







$var ident. , ident , . , .





- , , . , $var - , uncover ( , ).





, Rust , , : . , ? , . :





let unwrapped = uncover!(x);







:





let unwrapped = match x{







    Some(t) => t,







    None => panic!(“None value”)







};







- . , ( - inline-).  





let x = 2i32;







let unwrapped = uncover!(x);







, - . -, , .





Summary

, , , ? , . , , ? O(1) : list![1,2,3] ? ? , macro_rules! -, , proc_macro, syn, qoute TokenTree, - .





That, in fact, is all. Writing macros using macro_rules is not so difficult, the main thing is to understand the basic rules. Maybe it will save your nerves and / or money. Of course, I did not touch on the most interesting in this article, this is the simplest of what is. The purpose of this article is to show that macros are easy.





Write, if you want an article about proc_macro and syn, there really is something to see.








All Articles