Platform specific use statements


#1

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?


#2

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


#3

Oooh, there is a neat cfg_if! macro : https://github.com/rust-lang/libc/blob/master/src/macros.rs#L9


#4

@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.


#5

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