在跨平台应用程序中使用 std::os::linux 和 std::os::windows

Cat*_*ass 2 rust rust-cargo

我想创建一个访问文件系统的多平台应用程序,虽然我可以使用std::fs,但我发现操作系统特定的板条箱稍微简化了代码。因此,我使用 编写了一些代码std::os::windows::fs,并且它按预期工作。

我现在的问题是我想为 Windows 和 Linux 编写代码。为此,我创建了理论上将使用std::os::windows和的单独函数std::os::linux。然而,当尝试Linux forstd::os::windows Linux 上进行编译时,我遇到了不是可识别的 crate 的错误。

我的问题是,有什么方法可以让我std::os::windows在 Linux 上使用,反之亦然,或者只根据所使用的操作系统来编译特定的代码块?

我知道这是一个有点愚蠢的问题,考虑到我可以为不同的操作系统编写单独的模块,但我确实想尝试将所有内容包含在一个模块中。

我当前的代码大致如下:

pub fn run(os: &str, path: &str){
    let files = fs::read_dir(path).unwrap_or_else(|error: std::io::Error| {
        println!("Error: {error}");
        process::exit(1);
    });

    // The 'os' variable is obtained from std::env::consts::OS
    if os == "windows" {
        // Use std::os::windows in the following function
        printDir_win(files);
    } else if os == "linux" {
        // Use std::os::linux in the following function
        printDir_lin(files);
    } else {
        println!("{}OS not recognised: defaulting to std::fs methods{}","\x1b[31m","\x1b[0m");
        printDir(files);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jmb*_*Jmb 6

根据目标操作系统使用条件编译#[cfg(\xe2\x80\xa6)属性。这样编译器就不会尝试编译针对不同操作系统的代码:

\n
pub fn run(path: &str){\n    let files = fs::read_dir(path).unwrap_or_else(|error: std::io::Error| {\n        println!("Error: {error}");\n        process::exit(1);\n    });\n\n    // The \'os\' variable is obtained from std::env::consts::OS\n    #[cfg (target_os = "windows")]\n    {\n        // Use std::os::windows in the following function\n        use std::os::windows::*;\n        printDir_win(files);\n    }\n    #[cfg (target_os = "linux")]\n    {\n        // Use std::os::linux in the following function\n        use std::os::linux;\n        printDir_lin(files);\n    }\n    #[cfg (not (any (target_os = "windows", target_os = "linux")))]\n    {\n        println!("{}OS not recognised: defaulting to std::fs methods{}","\\x1b[31m","\\x1b[0m");\n        printDir(files);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

请注意,从组织的角度来看,将特定于平台的代码分组到一个模块中被认为是一种很好的做法,该模块抽象了通用 API 背后的差异:

\n
#[cfg (target_os = "windows")]\nmod platform {\n    use std::os::windows::*;\n    pub fn print_dir (files: std::fs::ReadDir) {\n        unimplemented!()\n    }\n}\n#[cfg (target_os = "linux")]\nmod platform {\n    use std::os::linux::*;\n    pub fn print_dir (files: std::fs::ReadDir) {\n        unimplemented!()\n    }\n}\n#[cfg (not (any (target_os = "windows", target_os = "linux")))]\nmod platform {\n    pub fn print_dir (files: std::fs::ReadDir) {\n        unimplemented!()\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

那么其余的代码就不需要到处检查操作系统来知道要调用哪个函数:

\n
pub fn run(path: &str){\n    let files = std::fs::read_dir(path).unwrap_or_else(|error: std::io::Error| {\n        println!("Error: {error}");\n        std::process::exit(1);\n    });\n    platform::print_dir (files);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

操场

\n