Applying a Rust attribute to more than one line

Viewed 962

To the best of my understanding of the Rust documentation, attributes are applied only to the line directly following an attribute. So, if I want to conditionally compile a line I can do this:

#[cfg(target_family = "unix")]
use termion::{color, style};

What happens when I want to conditionally compile two lines?

#[cfg(target_family = "unix")]
use termion::{color, style};
#[cfg(target_family = "unix")]
use termion::screen::*;

Is there a cleaner way for doing this?

1 Answers

There's no general grouping answer to my knowledge but there are specific solutions.

Most often, you can just use a block:

#[cfg(target_family = "unix")]
{
    // some code
}

use statements can always be grouped together, even when there's no common root:

#[cfg(target_family = "unix")]
use {
    termion::{color, style},
    std::io,
};

attributes are applied only to the line directly following an attribute

Not really. They're applied to the following "thing". There's a list of supported "things" in the documentation. It's not all what you'd probably want (it's not an if expression for example) but there's already a lot of covered ground.

Related