Commonly used attributes

I see a list of Rust attributes at It seems that commonly used attributes include derive and allow, and for writing tests, test and should_panic. Are there others that you use frequently?

I wish Rust referred to these as "decorators" instead of "attributes" because the latter isn't very searchable.

We use the #[doc] attribute very commonly in the Tokio crate. It lets us put the following label in our documentation:



Some others I use relatively often:

  • repr(C) or repr(transparent) to control memory layout
  • inline to mark functions that I want to be optimized away
  • cfg to handle multiple Cargo features
  • recursion_limit, but that's only because I like to push the type system to its limits-- it's probably not useful to most people

non_exhaustive can be useful on public types.


Is there a reason to prefer #[doc] over ///?

We are not using the #[doc = "text goes here"] form of the attribute. See the screenshot above for the kind of thing we typically use it for.

The #[doc] attribute

The doc attribute has more options though! These don't involve the text of the output, but instead, various aspects of the presentation of the output. We've split them into two kinds below: attributes that are useful at the crate level, and ones that are useful at the item level.

from the rustdoc book

The ones we use are:

  1. #[doc(hidden)] for macro internals
  2. #[doc(inline)] for some re-exports
  3. #[doc(no_inline)] for some re-exports
  4. #[doc(cfg(...))] for feature flag markers
  5. #![doc(html_root_url = "...")] for links to Tokio in other crates

Another one that is applied to a crate is #![feature(...)] when using nightly features.

#[no_mangle] is very useful in FFI situations along with #[link] when generating bindings.

#[must_use] can be used to tell people to use the result of a function:

fn foo() -> AThingThatDoesSomethingWhenUsedExplicitly {
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.