Answer#
Scattering #[cfg(target_os = ...)] through the whole program makes it hard to read and easy to break on the system you are not using. A cleaner design is to confine the differences to one module that exposes an identical interface:
mod platform {
#[cfg(windows)]
mod imp {
pub fn open_in_file_manager(path: &str) -> String {
format!("explorer.exe /select,{path}")
}
}
#[cfg(target_os = "macos")]
mod imp {
pub fn open_in_file_manager(path: &str) -> String {
format!("open -R {path}")
}
}
#[cfg(not(any(windows, target_os = "macos")))]
mod imp {
pub fn open_in_file_manager(path: &str) -> String {
format!("xdg-open {path}")
}
}
// One public function; callers never see which implementation was compiled.
pub use imp::open_in_file_manager;
}
fn main() {
println!("{}", platform::open_in_file_manager("report.pdf"));
}explorer.exe /select,report.pdfThe three imp modules have the same function with the same signature; only one exists in any build. The rest of the program calls platform::open_in_file_manager and nothing else. The sample returns the command text instead of running it so that it is safe to run and test; a real version would start the process with std::process::Command.
Guidelines:
- Same signature everywhere. If one system needs an extra argument, the common interface needs it, and the other systems ignore it.
- Keep the platform module small. Logic that is the same everywhere stays outside it.
- Always provide a fallback or an explicit
compile_error!for unsupported systems, so the failure message is yours. - Larger modules go in files:
#[cfg(windows)] #[path = "windows.rs"] mod imp;, ormod windows;andmod macos;with#[cfg]on each declaration. - Test the logic. Put the decision-making in portable functions that take the platform-specific parts as parameters, so tests on Windows cover most of it.
Common mistakes#
- Letting a
cfgbranch quietly diverge: the Windows version returns an error for a case and the macOS version ignores it. Define the contract in a doc comment on the common function. - Quoting or escaping arguments by hand for a command line. Pass them as separate
Command::argvalues.
Related questions#
Can a trait replace the modules?#
Yes: define a trait, implement it for a struct per system with #[cfg], and pick one with a type alias. Use it when you want to write tests with a fake implementation.
Sources#
- The Rust Reference, Conditional compilation: https://doc.rust-lang.org/reference/conditional-compilation.html (read 2026-12-05)
- The Rust Reference, the
pathattribute: https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute (read 2026-12-05)