What does an @ symbol mean in a Rust declarative macro?

后端 未结 1 714
星月不相逢
星月不相逢 2021-01-12 07:25

I have seen the @ symbol used in macros but I cannot find mention of it in the Rust Book or in any official documentation or blog posts. For example, in this St

相关标签:
1条回答
  • 2021-01-12 07:57

    In the pattern-matching part of a macro, symbols can mean whatever the author desires them to mean. A leading symbol @ is often used to denote an "implementation detail" of the macro — a part of the macro that an external user is not expected to use.

    In this example, I used it to pattern-match the tuple parameters to get a count of the tuple parameters.

    Outside of macros, the @ symbol is used to match a pattern while also assigning a name to the entire pattern:

    match age {
        x @ 0 => println!("0: {}", x),
        y @ 1 => println!("1: {}", y),
        z => println!("{}", z),
    }
    

    With a bit of a stretch, this same logic can be applied to the use in the macro — we are pattern-matching the tuple, but also attaching a name to that specific pattern. I think I've even seen people use something even more parallel: (count @ .... However, The Little Book of Rust Macros points out:

    The reason for using @ is that, as of Rust 1.2, the @ token is not used in prefix position; as such, it cannot conflict with anything. Other symbols or unique prefixes may be used as desired, but use of @ has started to become widespread, so using it may aid readers in understanding your code.


    rather than just creating another top-level macro

    Creating another macro is likely better practice, but only in modern Rust. Before recent changes to Rust that made it so you could import macros directly, having multiple macros could be tricky for end users who tried to selectively import macros.

    See also:

    • Internal rules in The Little Book of Rust Macros
    • Why must I use macros only used by my dependencies
    • What does the '@' symbol do in Rust?
    • Appendix B: Operators and Symbols
    0 讨论(0)
提交回复
热议问题