FAQ - Help and questions

How do I structure code so each operating system has its own implementation behind one function?

#cfg#modules#cross-platform#designpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Put each system's version in its own module with the same function names, select the module with cfg attributes, and re-export one of them under a common name. The rest of the program calls the common name and never mentions an operating system. Add a fallback module so other systems still build.

Checked with rustc 1.93.0, Windows 11; compiled and run on Windows only. The macOS and fallback modules were not compiled here; they contain only string formatting.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:

src/main.rsrust
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"));
}
text
explorer.exe /select,report.pdf

The 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:

  1. Same signature everywhere. If one system needs an extra argument, the common interface needs it, and the other systems ignore it.
  2. Keep the platform module small. Logic that is the same everywhere stays outside it.
  3. Always provide a fallback or an explicit compile_error! for unsupported systems, so the failure message is yours.
  4. Larger modules go in files: #[cfg(windows)] #[path = "windows.rs"] mod imp;, or mod windows; and mod macos; with #[cfg] on each declaration.
  5. 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 cfg branch 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::arg values.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet