Search code examples
rustattributes

What are the possible formats for attributes in Rust?


I have come across attributes and observed that they sometimes come in different formats, but yet I was unable to find a place that actually explains these formats.

so far I have observed attributes of this form:

  1. #[attributes] (e.g., #[test])
  2. #[key=value] (e.g., #![crate_type = "lib"])
  3. #[method(param)] (e.g., #[cfg(test)])
  4. #[method(key=value)] (e.g., #[cfg(target_os = "linux")])

Question is, are these all the supported formats? And in what situation would you use one format over the other ones?


Solution

  • The reference covers the exact syntax, but what Rust will accept boils down to:

    #[any::path]
    #[any::path = some + expression]
    #[any::path(pretty much anything)] // can also use {} and [] instead
    

    From there, it's up to what the individual procedural macro the attribute is associated with to parse the attribute contents, and determine what is and is not valid.