如何标记条件编译的 use 语句?

Jos*_*ung 3 syntax conditional-compilation rust

是否可以将某些包含标记为仅包含在相关操作系统中?

例如,您可以执行以下操作:

#[cfg(unix)] {
    use std::os::unix::io::IntoRawFd;
}
#[cfg(windows)] {
   // https://doc.rust-lang.org/std/os/unix/io/trait.AsRawFd.html  suggests this is equivalent?
   use std::os::windows::io::AsRawHandle;
}
Run Code Online (Sandbox Code Playgroud)

试图编译上面的代码给了我语法错误(即error: expected item after attributes)。

我正在尝试修补我在 GitHub 上找到的 Rust 项目以在 Windows 上编译(同时仍然使其保留在其现有目标上编译的能力 - 即 Unixes 和 WASM)。目前我遇到了一个问题,其中一些文件从std::os(例如use std::os::unix::io::IntoRawFd;)导入特定于平台的部分,这最终破坏了 Windows 上的构建。

注意:我正在使用 Rust Stable (1.31.1) 而不是每晚使用。

Che*_*evy 5

您正在寻找的语法是:

#[cfg(target_os = "unix")]
use std::os::unix::io::IntoRawFd;

#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawHandle;
Run Code Online (Sandbox Code Playgroud)