skip to content

As the lead on a Rust file-watching library with Linux, macOS and Windows back ends, how would you structure its platform-specific code, and why?

level: principalimportance: should knowfreq 30%

answer

  1. where the cfg lines live
  2. one public type, private back ends
  3. a sys module choosing imp
  4. every target needs its own build

basics

~20 s

Keep the public API platform-free and put each back end in its own module behind a crate-private sys facade that selects one with cfg_select! or #[cfg], plus a fallback or compile_error!. Scattered item-level cfg suits only a few small differences.

solid answer

~40 s

I put the split at a module boundary. The public `Watcher` is written once and holds a crate-private `sys::Backend`; `sys` selects exactly one of `linux`, `macos`, `windows` or a polling fallback with `cfg_select!`, or with `#[cfg]` pairs if our minimum supported Rust version predates 1.95, and each module provides the same crate-private surface. That keeps every cfg line in one file, which is the shape the standard library uses with `use unix as imp`. Unix-only extras go in a `#[cfg(unix)] pub mod unix` extension trait, as `std::os::unix::fs::PermissionsExt` does, so the portable API stays portable. One-off differences such as a separator stay as `cfg!` or a gated constant. The cost is that a back end is only type-checked when someone builds its target, so CI must build every target and feature combination.

code

rust · 10 lines
rust
// src/sys.rs: picks exactly one back end; each file under src/sys/
// defines the same crate-private `Backend` with `new()` and `name()`.
cfg_select! {
    target_os = "linux" => { mod linux; use linux as imp; }
    target_os = "macos" => { mod macos; use macos as imp; }
    windows => { mod windows; use windows as imp; }
    _ => { mod poll; use poll as imp; }
}

pub(crate) use imp::Backend;

go deeper

for a junior

Recall that platform code can live in separate modules chosen by cfg, so the rest of the crate never mentions a platform.

for a middle

Explain how a sys module with use linux as imp, or cfg_select!, picks one back end and why each must expose identical signatures.

for a senior

Show why a CI build per target and per feature combination is mandatory once back ends are cfg-gated, and how a fallback or compile_error! states support.

for a principal

Own the tradeoff between scattered cfg and a facade, the MSRV cost of cfg_select!, extension traits for platform extras, and how features stay orthogonal to platforms.

## The decision A file-watching library needs a different mechanism on each platform: inotify on Linux, FSEvents on macOS, `ReadDirectoryChangesW` on Windows, and perhaps a polling fallback elsewhere. Rust gives you the tools — `#[cfg]`, `cfg!`, `cfg_attr` and, since 1.95, `cfg_select!` — but not the layout. The lead's decision is **where the `cfg` lines live**, and there are two broad options. - **Scattered item-level cfg.** Each function that differs gets its own `#[cfg(target_os = ...)]` copies, side by side, wherever it happens to be used. - **Per-platform modules behind one facade.** Each back end is a module; a crate-private `sys` module selects exactly one; the public API is written once against that selection. Neither is wrong in general. The judgment is about scale, review cost and how drift gets caught. ## The facade shape The facade layout has four parts: 1. **A public API written once.** `Watcher`, its events and its errors live in platform-free code and hold a crate-private `sys::Backend`. Users and documentation see one API on every target. 2. **A selector.** `src/sys.rs` picks one back end with `cfg_select!` — `target_os = "linux" => { mod linux; use linux as imp; }` and so on, with `_` for the fallback — and re-exports `imp::Backend`. If the crate's minimum supported Rust version is below 1.95, the same selection is written with `#[cfg]` pairs and a `not(any(...))` fallback. 3. **Back ends with an identical crate-private surface.** Each of `sys/linux.rs`, `sys/macos.rs`, `sys/windows.rs` and `sys/poll.rs` defines `Backend` with the same method signatures. Some teams state that contract as a crate-private trait; others rely on matching inherent methods. 4. **An explicit answer for every target.** Either the `_` arm provides a portable fallback, or `compile_error!("unsupported platform")` says so; never a gap that surfaces as an unexplained E0425. The standard library uses the same shape: its file-system layer has a `cfg_select!` that declares `mod unix; use unix as imp;` for Unix-family targets and the equivalent for Windows and other systems, and the rest of the layer only talks to `imp`. ## Platform-only extras Some capabilities exist on one platform only — Unix permission bits, Windows file attributes, a Linux-specific watch flag. Putting them on the portable type behind `#[cfg(unix)]` makes that type's API differ by target, which surprises users and breaks code that is moved between platforms. The standard library's answer is an **extension trait in a platform module**: `std::os::unix::fs::PermissionsExt` adds `mode`, `set_mode` and `from_mode` to `std::fs::Permissions`, but only code that imports it from the Unix-only module can call them. A watcher library can mirror this with `#[cfg(unix)] pub mod unix` holding an extension trait for `Watcher`. ## The tradeoffs | Concern | Scattered `#[cfg]` | Modules behind a facade | |---|---|---| | A few small differences | cheap and readable | heavy scaffolding | | Many functions and real state | cfg lines everywhere, hard to review | one file chooses, each back end reads top to bottom | | Public API consistency | easy to let signatures drift per target | one definition for all targets | | Adding a platform | edit every gated site and every fallback | add one module and one arm | | Minimum Rust version | any | any with `#[cfg]`; 1.95 or later with `cfg_select!` | Small differences — a path separator, a default directory, one system call — are better served by a gated constant, a `cfg!` choice or a single gated function. The module split pays off once back ends hold state and share many operations. ## What the layout cannot do for you The weakness of every cfg-based design is the same: **code removed by a false predicate is never type-checked on that host**. A developer on macOS can break the Linux back end and see a green build. The layout makes that drift easier to find, not impossible. So the decision comes with policy: - CI builds and tests **every supported target**, not only the developers' hosts; cross-compiling and the target setup belong to Cargo's tooling. - CI builds the **feature combinations** that matter — default, no default features, and the metrics feature on — because a gate can be wrong in only one of them. - The `unexpected_cfgs` lint is denied, so a misspelled `target_os` value or feature name fails the build instead of silently removing a back end. - Optional integrations such as metrics stay **orthogonal to platforms**: one `#[cfg(feature = "metrics")]` module the facade calls from a few gated statements, rather than feature gates inside every back end. ## What a strong answer sounds like A principal-level answer does not recite attributes. It states the choice — scattered cfg for a handful of differences, a facade once back ends are real — and defends it with the review and drift costs. It mentions the MSRV cost of adopting `cfg_select!`, extension traits for platform extras, an explicit fallback or `compile_error!`, and the CI matrix that the whole approach depends on, since no layout can type-check code the compiler has removed.

  • Should each back end implement a private trait, or just inherent methods with matching signatures?
    Either works, because only one back end is compiled at a time. A crate-private trait writes the contract down once and gives each back end a precise error when it drifts; inherent methods are simpler and avoid a trait nobody else implements. Drift is still caught only when that target is built, so neither replaces a CI build per target.
  • Where should the optional metrics integration live in this layout?
    In one module, `#[cfg(feature = "metrics")] mod metrics;`, with the facade calling it from a small number of gated statements, rather than `cfg(feature)` lines across every back end. That keeps the feature orthogonal to the platform split and makes the feature-on and feature-off builds easy to test in CI.
  • When is splitting into per-platform modules the wrong call?
    When the differences are a handful of constants or one system call. A module per platform adds indirection and duplicated scaffolding; a gated constant, a `cfg!` choice or one gated function is cheaper to read. The module split pays off once the back ends hold real state and many functions.

  • Scatter #[cfg] on every function; a facade module is just extra indirection.
  • Expose each platform's type publicly and let users pick with their own cfg.
  • cfg! everywhere is fine, because the optimiser deletes the other platforms' calls.
  • Building on the developer's own machine is enough to check every back end.
  • Unix-only options belong directly on the portable type behind #[cfg(unix)].