【问题标题】:Applying a Rust attribute to more than one line将 Rust 属性应用于多行
【发布时间】:2020-02-24 09:27:14
【问题描述】:

就我对the Rust documentation 的理解而言,属性仅应用于直接跟在属性之后的行。所以,如果我想conditionally compile 一行我可以这样做:

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

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

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

有没有更清洁的方法来做到这一点?

【问题讨论】:

  • 好吧,在这种情况下,您可以将这些导入合并到一行:use termion::{coloe, style, screen::*}。但一般来说它可能无法回答您的问题。
  • @edwardw,真的,我正在寻找更一般的答案
  • 旁注:至少有one crate在解决终端跨平台使用问题。
  • @DenysSéguret 谢谢我不知道!

标签: rust attributes conditional-compilation


【解决方案1】:

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

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

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

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

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

属性仅应用于直接跟在属性后面的行

不是真的。它们适用于以下“事物”。有一个受支持的“事物”列表in the documentation。这并不是您可能想要的全部内容(例如,它不是 if 表达式),但已经有很多内容了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多