我想创建一个访问文件系统的多平台应用程序,虽然我可以使用std::fs
个,但我发现特定于操作系统的机箱稍微简化了代码.所以,我用std::os::windows::fs
编写了一些代码,它像预期的那样工作.
我现在的问题是,我想同时为Windows和Linux编写代码.为此,我创建了不同的函数,理论上将分别使用std::os::windows
和std::os::linux
.然而,当我试图编译onLinux forLinux时,我遇到了一个错误,即std::os::windows
不是一个可识别的 crate .
我的问题是,有没有办法让我在Linux上使用std::os::windows
,反之亦然,或者只编译特定的代码块,这取决于使用Cargo的操作系统?
我知道这是一个有点愚蠢的问题,考虑到我可以为不同的操作系统编写单独的模块,但我确实想try 将所有内容包含在一个模块中.
我目前的代码大致如下:
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);
}
}