How to mark use statements for conditional compila

2019-08-16 14:12发布

Is it possible to mark certain includes to only get included on relevant OS's?

For example, can you do something like:

#[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;
}

Trying to compile the above code gives me syntax errors (i.e. error: expected item after attributes).

I'm trying to patch a Rust project I found on GitHub to compile on Windows (while still making it retain the ability to be compiled on its existing targets - i.e. Unixes & WASM). Currently I'm running into a problem where some of the files import platform-specific parts from std::os (e.g. use std::os::unix::io::IntoRawFd;), which ends up breaking the build on Windows.

Note: I'm using Rust Stable (1.31.1) and not nightly.

1条回答
做个烂人
2楼-- · 2019-08-16 14:20

The syntax you are looking for is:

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

#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawHandle;
查看更多
登录 后发表回答