skip to content

Modules and Crates

Rust code is organised into crates and a module tree with private-by-default visibility. Interviewers ask about paths, re-exports, visibility, #[cfg] and what counts as a breaking change.

on this pageshow

explore

questions

25

In Rust, how do you write one function with separate Linux, macOS and Windows bodies using `#[cfg]`, and what happens to the unused ones?

level: juniorimportance: must knowfreq 58%

answer

  1. one copy per target
  2. target_os key-value predicate
  3. removed before type checking
  4. fallback with not(any(...))

basics

~20 s

Write one copy of the function per platform, each gated by a cfg predicate such as target_os = "linux" or windows, plus a not(any(...)) fallback. rustc deletes every copy whose predicate is false before it resolves names or checks types.

solid answer

~30 s

I write the function once per platform with the same signature: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(windows)]`, and a fallback under `#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]`. The compiler evaluates each predicate against the target and removes every item whose predicate is false, so exactly one `backend_name` is left by the time names are resolved and types are checked. The removed copies still have to parse, but they are never type-checked on this target, which is why CI has to build each platform. If no copy survives, callers fail with E0425; if two survive, the duplicate fails with E0428.

code

rust · 23 lines
rust
#[cfg(target_os = "linux")]
fn backend_name() -> &'static str {
    "inotify"
}

#[cfg(target_os = "macos")]
fn backend_name() -> &'static str {
    "FSEvents"
}

#[cfg(windows)]
fn backend_name() -> &'static str {
    "ReadDirectoryChangesW"
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn backend_name() -> &'static str {
    "polling"
}

fn main() {
    println!("watching with {}", backend_name());
}

go deeper

for a junior

Recall the shape: one copy per platform with target_os or windows, a not(any(...)) fallback, and the same signature on every copy.

for a middle

Explain that removal happens before name resolution and type checking, why removed code must still parse, and the E0425 and E0428 failures when zero or two copies survive.

for a senior

Show you know cfg-gated code rots silently on other hosts, so every target needs a CI build, and pick unix versus target_os deliberately for the API being called.

for a principal

Frame scattered item-level cfg as fine for a few functions but costly at scale, and argue when to move to per-platform modules behind one facade.

## What `#[cfg]` does **Conditional compilation** means some source code is compiled only under certain conditions. In Rust the main tool is the **`cfg` attribute**: you attach `#[cfg(predicate)]` to a piece of code, and rustc evaluates the **configuration predicate** against the target it is compiling for. The Reference states the effect precisely: if the predicate is true, the attribute is simply dropped and the code stays; if it is false, **the form is removed from the source code**. That removal happens early, during expansion, before **name resolution** (working out what each path refers to) and before **type checking**. So for a given build, a removed function does not exist at all: it is not compiled, not type-checked, not linked, and not callable. Writing one function per platform is therefore not "several functions, one of which runs" — it is "one function, chosen at compile time". ## The predicates you use for platforms A predicate is built from **configuration options**, which are either bare names (`unix`) or key-value pairs (`target_os = "linux"`). The compiler sets the target ones for you; you can list them for your host with `rustc --print cfg`. | Predicate | What it tests | Example values | |---|---|---| | `target_os = "..."` | the operating system | `"linux"`, `"macos"`, `"windows"`, `"ios"`, `"freebsd"`, `"none"` | | `target_family = "..."` | the broad family | `"unix"`, `"windows"`, `"wasm"` | | `unix`, `windows` | shorthand names | set when the family is unix or windows | | `target_arch = "..."` | the CPU architecture | `"x86_64"`, `"aarch64"`, `"arm"` | | `target_pointer_width = "..."` | pointer size in bits | `"16"`, `"32"`, `"64"` | | `debug_assertions` | builds without optimisations, by default | a bare name | Three operators combine predicates: - **`all(a, b, ...)`** is true when every predicate is true, and true for an empty list. - **`any(a, b, ...)`** is true when at least one is true, and false for an empty list. - **`not(a)`** inverts one predicate. Note what is *not* a built-in name: there is no bare `macos` or `linux`. `#[cfg(macos)]` is simply never true, and under Cargo the `unexpected_cfgs` lint warns about it. Use `target_os = "macos"`. ## Writing one function per platform The recipe has four steps: 1. Write each platform's version with the **same name and signature**. 2. Gate each with its predicate: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(windows)]`. 3. Add a **fallback** whose predicate is the negation of all the others: `#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]`. It can contain a portable implementation, or you can replace it with `compile_error!("unsupported platform")` to make the limitation explicit. 4. Call the function normally. Callers never mention a platform. The predicates must be **mutually exclusive and exhaustive** for the targets you support, because rustc does nothing to choose between survivors: - If **no** copy survives, every call fails with **E0425**, "cannot find function `backend_name` in this scope", and rustc adds a note that an item was configured out. - If **two** copies survive — say one under `unix` and one under `target_os = "macos"` on a Mac — the second is a duplicate definition, **E0428**, "the name `backend_name` is defined multiple times". The `cfg_select!` macro, stable since Rust 1.95, removes most of this bookkeeping by taking the first matching arm. ## What removal does and does not skip Removal is thorough, but it is not "ignore the text": - **Parsing still happens.** The attribute is attached to a parsed item, so a syntax error such as `let x = ;` inside a `#[cfg(windows)]` function breaks the build on every platform. - **Type checking does not.** A type mismatch or a call to a function that only exists on Windows inside the Windows copy goes unnoticed on Linux and macOS. This is why platform code can rot quietly, and why a crate with platform branches needs a CI build for each target it supports. - **Nothing reaches the binary.** The removed code is not compiled or linked, so it costs no size and cannot be called by accident. ## Where `#[cfg]` can go The Reference allows `cfg` anywhere attributes are allowed, which in practice means: - **items**: functions, structs, `impl` blocks, `mod` and `use` declarations; - **statements** inside a function body, such as a `#[cfg(debug_assertions)]` logging line; - **struct fields**, **enum variants** and **match arms**; - **elements** of array, tuple and struct-literal lists, such as `vec![1, #[cfg(unix)] 2]`. A bare expression is the exception: `let x = #[cfg(unix)] 5;` fails with E0658, "attributes on expressions are experimental". To choose a *value* per platform, use the `cfg!` macro when both values are valid everywhere, or `cfg_select!` in expression position. In an interview, the strong answer names the predicate syntax, says the false copies are removed before type checking, and adds the two consequences: you need a fallback for unsupported targets, and you need to build every target to know the hidden copies still compile.

  • What happens if the crate only has the Linux, macOS and Windows copies and someone builds it for FreeBSD?
    All three predicates are false, so all three items are removed and every call site fails with E0425, "cannot find function `backend_name` in this scope"; rustc adds a note that an item was configured out. Either add a fallback under `not(any(...))`, or state the limitation with `#[cfg(not(any(...)))] compile_error!("unsupported platform");` so the error says why.
  • Why can a `#[cfg(windows)]` function containing a type error still build on macOS?
    The item is removed before name resolution and type checking, so its body is never type-checked for that target. It must still parse, because the attribute is attached to a parsed item: a syntax error such as `let x = ;` fails on every platform. A type error only shows up when someone compiles for Windows.
  • What does `#[cfg(unix)]` select, and is it the same as Linux?
    `unix` is set whenever `target_family = "unix"` is set: Linux, macOS, the BSDs, Android, iOS and others, and even `wasm32-unknown-emscripten`, which reports both the unix and wasm families. It is broader than `target_os = "linux"`, so use it for code that relies on POSIX behaviour and `target_os` for one specific kernel API.

  • The copies for other platforms are compiled and simply never called at run time.
  • Code in a disabled cfg branch is skipped entirely, so it does not even have to parse.
  • cfg(macos) or cfg(linux) targets that operating system; only unix and windows are bare names.
  • A missing platform branch shows up as a panic when that platform runs the program.
  • cfg(unix) selects only Linux, not macOS or the BSDs.
open as a page

In Rust, a CLI's main.rs says mod config; — where does rustc look for its code, and why is an undeclared src/storage.rs ignored?

level: juniorimportance: must knowfreq 70%

basics

~20 s

rustc loads mod config; from src/config.rs or src/config/mod.rs and makes it crate::config. It starts at the crate root and follows mod declarations, so a file that no mod (or include! call) names is never parsed or compiled.

open as a page

In Rust, what do paths beginning with `crate::`, `self::` and `super::` resolve from, and when do you use each?

level: juniorimportance: must knowfreq 65%

basics

~20 s

crate:: starts at the crate root, self:: at the current module and super:: at its parent. Use crate:: for distant items, super:: for a parent or sibling, and self:: only to stress that a name is local.

open as a page

In Rust, what visibility do items and struct fields get by default, and what does marking them pub change?

level: juniorimportance: must knowfreq 76%

basics

~20 s

Every Rust item and struct field is private to its defining module and that module's descendants unless marked pub. Marking a struct pub leaves its fields private; only enum variants and pub trait items inherit their parent's visibility.

open as a page

How does `pub use` let a Rust library expose `geometry::Point` and a `geometry::prelude` when `Point` is defined deep inside a private module?

level: middleimportance: must knowfreq 55%

basics

~20 s

A pub use at the crate root, such as pub use shapes::point::Point, publishes the item as geometry::Point while it stays defined in a private module. A pub mod prelude of re-exports gives users one glob import.

open as a page

Why does rustc reject `Temperature { kelvin: -5.0 }` outside its module, and how does that protect the type's invariant?

level: middleimportance: must knowfreq 62%

basics

~20 s

Because kelvin is a private field, rustc rejects any Temperature struct literal outside its module with E0451. Outside code must go through a constructor such as from_kelvin, which refuses negative values, so every Temperature it holds is valid.

open as a page

In a Rust HTTP-client library, is adding a `TooManyRedirects` variant to the public `Error` enum a minor release, and what does `#[non_exhaustive]` change?

level: middleimportance: should knowfreq 50%

basics

~20 s

Not on a plain public enum: downstream matches listing every variant fail with E0004, so a new variant is major. If the enum was #[non_exhaustive] from its first release, other crates must keep a wildcard arm, and new variants are minor.

open as a page

In Rust, why is adding a `pub` field to a library's all-public `Config` struct a major change, and how does `#[non_exhaustive]` avoid it?

level: middleimportance: should knowfreq 42%

basics

~20 s

Other crates can build an all-public struct with a literal or destructure it field by field; both break when a field is added. With #[non_exhaustive], other crates cannot use literals and must write .. in patterns, so new fields are minor.

open as a page

In Rust, why does `if cfg!(windows) { windows_dir() }` fail on Linux when `windows_dir` is declared under `#[cfg(windows)]`?

level: middleimportance: should knowfreq 48%

basics

~20 s

cfg!(windows) only expands to the literal true or false; it removes nothing. Both if branches stay in the program and must compile on every target, but the #[cfg(windows)] item was deleted on Linux, so the call fails with E0425.

open as a page

In Rust 1.95 and later, what does `cfg_select!` give you over a stack of `#[cfg]` items with a `not(any(...))` fallback?

level: middleimportance: should knowfreq 32%

basics

~20 s

cfg_select!, stable since Rust 1.95, tries its predicates in order and expands only the first true arm, with _ as a fallback and a compile error if none match. You stop repeating negated predicates, and overlapping ones no longer collide.

open as a page

In Rust, commands.rs declares pub mod run; — where must run's file go, and how do commands.rs and commands/mod.rs differ?

level: middleimportance: should knowfreq 55%

basics

~10 s

run's code goes in src/commands/run.rs (or src/commands/run/mod.rs). src/commands.rs and src/commands/mod.rs are two allowed locations for the same module's own file; using both at once is error E0761.

open as a page

In Rust, why do `use crate::shapes::Point;` and `use crate::svg::Point;` in one module fail with E0252, and how do you fix it?

level: middleimportance: should knowfreq 45%

basics

~20 s

Each module holds one binding per name in each namespace, and both imports bind Point in the type namespace, so rustc reports E0252 at the second use. Rename one with as, or import the parent module and write svg::Point.

open as a page

In Rust, who may use an item marked pub(crate), pub(super) or pub(in path), and what can these restrictions not override?

level: middleimportance: should knowfreq 48%

basics

~20 s

pub(crate) opens an item to the whole crate, pub(super) to the parent module, and pub(in path) to a named ancestor module. They only narrow pub: the path must be an ancestor (E0742), and every module on the way must still be visible.

open as a page

Why does moving a dependency from 1.x to 2.0 force a major release of a Rust library whose public function takes that dependency's `Url` type?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Cargo can build 1.x and 2.x of one crate side by side, and their Url types are distinct. Callers passing a 1.x Url to a function now expecting the 2.0 Url get E0308, so the dependency's major bump becomes the library's.

open as a page

When a Rust library adds a method to its public `Middleware` trait, when is that a major release, and why might the crate seal the trait instead?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A method with no default body is major: every outside implementation fails with E0046. A defaulted one is usually safe but can cause E0034 ambiguity. A sealed trait has no outside implementations, so it can gain methods in a minor release.

open as a page

In a Rust library with an optional `serde` feature, how do `#[cfg(feature = "serde")]` and `#[cfg_attr(feature = "serde", derive(...))]` differ, and what catches a misspelled feature name?

level: seniorimportance: should knowfreq 40%

basics

~20 s

#[cfg(feature = "serde")] removes the whole item when the feature is off; #[cfg_attr(feature = "serde", derive(Serialize))] keeps the item and adds the derive only when it is on. A misspelled feature name triggers the unexpected_cfgs warning, which Cargo enables since 1.80.

open as a page

In a Rust package with src/lib.rs and src/main.rs that both declare mod storage;, why does passing a storage::Record to a library function fail with E0308?

level: seniorimportance: should knowfreq 40%

basics

~20 s

lib.rs and main.rs are roots of two crates, so each mod storage; compiles storage.rs into its own tree, making two distinct Record types. Declare storage only in the library and use it from main.rs through the package's crate name.

open as a page

In Rust, when `use shapes::*;` and `use plot::*;` both export `Point`, when does rustc report E0659, and what outranks a glob import?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Conflicting glob imports compile until the name is used; then rustc reports E0659, Point is ambiguous. A local item or an explicit use silently outranks any glob, and globs in turn outrank the standard prelude.

open as a page

A Rust library's pub fn returns a private struct and builds with only a private_interfaces warning; why can downstream crates still not call it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Since Rust 1.74 a private type in a pub signature is only the private_interfaces warning in the library, but a downstream call still fails type privacy with "type thermo::Calibration is private". Make the type pub, or the function pub(crate).

open as a page

As lead of a widely used Rust HTTP-client crate approaching 1.0, what policy would you set for `#[non_exhaustive]`, deprecation and cutting major versions?

level: principalimportance: should knowfreq 30%

basics

~20 s

Decide before 1.0, type by type: #[non_exhaustive] on error enums, open-ended enums and option structs, exhaustive enums for closed sets. Deprecate with #[deprecated(since, note)] in a minor release, remove only in a major, and batch breaking changes into rare majors.

open as a page

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%

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.

open as a page

A Rust library's patch release keeps an `Rc` alive across an `.await` inside `pub async fn fetch`; why do some downstream builds stop compiling?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Send is an auto trait: the future fetch returns is Send only if everything it holds across .await is Send. An Rc held there removes Send, so callers that need a Send future stop compiling: a breaking change.

open as a page

In Rust, how does a #[path] attribute on a mod declaration change where rustc loads the module's file, and how do enclosing inline mod blocks change that lookup?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

#[path = "x.rs"] on mod name; loads that file instead of name.rs, relative to the declaring file's directory, while the module path stays unchanged. Inside inline mod blocks the base directory gains one component per enclosing block.

open as a page

A Rust binary declares `mod geometry` and depends on a crate also named `geometry`; what does `use geometry::origin;` resolve to in each module?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

At the root, the local mod geometry shadows the crate, so the import fails with E0432 if the module lacks origin; in nested modules it reaches the dependency. Write ::geometry for the crate and crate::geometry for the module.

open as a page

In a Rust library, when is a pub item not part of the crate's public API, and what does the unreachable_pub lint flag?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

A pub item in a private module that is neither re-exported nor reachable through a public signature is effectively pub(crate). The allow-by-default unreachable_pub lint flags such items and suggests pub(crate), so the source states the API's real reach.

open as a page