Platform specific use statements

I need to do a bunch of platform specific imports, and didn't want to have to annotate each and every use statement with a #[cfg()] directive. So I came up with this:

#[cfg(windows)]
mod _plat_specifics {
    pub use winapi::SOCKADDR as sockaddr;
    pub use winapi::SOCKADDR_IN as sockaddr_in;
    pub use winapi::IN_ADDR as in_addr;
    pub use winapi::{AF_INET, AF_INET6};
    pub use winapi::{SOCK_STREAM, SOCK_DGRAM};
}

#[cfg(not(windows))]
mod _plat_specifics {
    pub use libc::{sockaddr, sockaddr_in, in_addr};
    pub use libc::{AF_INET, AF_INET6};
    pub use libc::{SOCK_STREAM, SOCK_DGRAM};
}

use _plat_specifics::*;

Is this the recommended approach? Any other ideas?

1 Like

This is similar to the approach libc uses, so I guess it's okay:

https://github.com/rust-lang/libc/blob/master/src/unix/mod.rs#L830-L851

Oooh, there is a neat cfg_if! macro : libc/macros.rs at master · rust-lang/libc · GitHub

@eminence You code is reasonable but the underscore prefix isn't idiomatic - just name it normally. The cfg_if! macro is neat. Not sure if there's anything preventing it from being published on its own.

cfg_if! can be found on its own here: https://crates.io/crates/cfg-if

2 Likes