将 Rust 属性应用于多行

Yuv*_*dam 3 attributes conditional-compilation rust

据我对Rust 文档的最佳理解,属性仅应用于直接跟随属性的行。所以,如果我想有条件地编译一行,我可以这样做:

#[cfg(target_family = "unix")]
use termion::{color, style};
Run Code Online (Sandbox Code Playgroud)

当我想有条件地编译两行时会发生什么?

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

有没有更干净的方法来做到这一点?

Den*_*ret 6

据我所知,没有通用的分组答案,但有特定的解决方案。

大多数情况下,你可以只使用一个块:

#[cfg(target_family = "unix")]
{
    // some code
}
Run Code Online (Sandbox Code Playgroud)

use 语句总是可以组合在一起,即使没有共同的根:

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

属性仅应用于直接跟随属性的行

并不真地。它们应用于以下“事物”。文档中有一个受支持的“事物”列表。这不是您可能想要的全部(if例如,它不是表达式),但已经有很多覆盖面。