How to mark use statements for conditional compilation? [duplicate]

↘锁芯ラ 提交于 2019-12-11 12:08:53

问题


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:


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;


来源:https://stackoverflow.com/questions/54515989/how-to-mark-use-statements-for-conditional-compilation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!