Rust?中的条件导入

bnl4lu3b  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(137)

我有一个服务器应用程序,必须在Windows和Linux系统上运行。问题从我使用的mdns/zeroconf模块开始。
我两者都用:
1.用于Linuxzeroconfhttps://docs.rs/zeroconf/latest/zeroconf/
1.用于Windowsastro_dnssdhttps://github.com/astrohq/astro-dnssd

    • 为什么我必须使用2个模块来做同样的事情?**

由于zeroconf支持Linux但不支持Windows,而astro_dnssd使用bonjour-compatibility layer on top of Avahi for Linux which no longer supported,但astro_dnssd在Windows上运行良好,因此我不得不使用2个模块来完成基本相同的任务

    • 我的main.rs:**
// asto_dnssd can be compiled on both Windows and Linux, but doesn't work as intended on Linux
use astro_dnssd::DNSServiceBuilder;

// this modules doesn't even compile on Windows
// so I had to manually disable this line and everything that uses zeroconf to run my server app on Windows, including the "Cargo.toml" file
use zeroconf::prelude::*;
use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};
    • 问题是:**

到目前为止,每当我在Windows上工作时,我必须手动禁用zeroconf(通过注解该行),当我在Linux上工作时,我必须再次启用它。这是一项乏味的工作,从长远来看是不可持续的。是否可以使用env变量或env::consts::OS来检测并在Rust中进行"条件导入"?例如:

let current_os = env::consts::OS;
match current_os {
        "windows" => {
            use astro_dnssd::DNSServiceBuilder;
            //... the rest of the code
        }
        "linux" => {
            use zeroconf::prelude::*;
            use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};
            // ... the rest of the code
        }
        _ => {
            panic!("This operating system is not supported yet")
        }
    };
zdwk9cvp

zdwk9cvp1#

有条件导入

在Rust中可以使用cfg进行条件编译。

#[cfg(target_os = "linux")]
use zeroconf::prelude::*;
#[cfg(target_os = "linux")]
use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};

#[cfg(target_os = "windows")]
use astro_dnssd::DNSServiceBuilder;

为了提高可读性,您可能希望将特定于平台的部分放在模块中。

#[cfg(target_os = "linux")]
mod details {
    use zeroconf::prelude::*;
    use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};

    // Define structs, functions, ...
    pub fn perform_platform_specific_operation() {}
}

#[cfg(target_os = "windows")]
mod details {
    use astro_dnssd::DNSServiceBuilder;

    // Define structs, functions, ...
    pub fn perform_platform_specific_operation() {}
}

fn main() {
    details::perform_platform_specific_operation();
}

有条件货物依赖性

请参阅Cargo Book中的平台特定依赖项。例如,Cargo.toml中的以下行可以满足您的需要(根据您自己的需要调整版本号)。

[target.'cfg(windows)'.dependencies]
astro_dnssd = "0.1.0"

[target.'cfg(unix)'.dependencies]
zeroconf = "0.1.0"

相关问题