Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 7 · Modules & crates

    7.2Crates, workspaces & features

    How a Rust project grows from one crate to a workspace, how dependencies and their versions work, and how features and cfg switch code on and off at compile time.

    About 25 minutesIntermediate

    On this page
    1. Concept map
    2. Packages and crates
    3. Workspaces
    4. Dependencies and versions
    5. Features: optional parts of a crate
    6. Conditional compilation with cfg
    7. Which one should I use?
    8. Under the hood
    9. Cargo.lock for programs and libraries
    10. Common pitfalls
    11. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Project filepackage.jsonBilling.csprojCargo.toml
    Program or libraryA bin entry, or main / exports, in package.json<OutputType>Exe</OutputType>, or a class librarysrc/main.rs (a binary crate) or src/lib.rs (a library crate)
    Several projects in one repositorynpm or pnpm workspacesA solution file with project referencesA Cargo workspace: [workspace] in the root Cargo.toml
    Depending on a sibling project"billing": "workspace:*"<ProjectReference Include="../Billing/Billing.csproj" />billing = { path = "../billing" }
    Optional parts of a packageSeparate add-on packages, or subpath exportsSeparate add-on packagesCargo features: [features] and #[cfg(feature = "json")]
    Code only some builds includeNot in the language; bundlers replace process.env.NODE_ENV#if DEBUG, [Conditional("DEBUG")]#[cfg(debug_assertions)], cfg!(…)

    The previous lesson organized code inside a crate. This one organizes crates: where TypeScript has packages, package.json and workspaces,where C# has projects, .csproj files, solutions and NuGet packages, Rust has crates, Cargo.toml and workspaces. It also covers the two ways Rust leaves code out of a build: features that a crate’s users switch on, and cfg conditions such as “debug build” or “Windows only”.

    Packages and crates

    Three words that are easy to mix up:

    • A package is a folder whose Cargo.toml has a [package] section. It’s what cargo new creates and what you publish.
    • A crate is one thing the compiler builds from a package: a library or a binary (an executable). A crate is also the unit of compilation: rustc compiles a whole crate at once.
    • A module is a scope inside a crate, which the previous lesson covered.

    Cargo finds the crates in a package by file name, so there’s nothing to register:

    billing/
    ├── Cargo.toml
    └── src/
        ├── lib.rs         the library crate, named billing
        ├── main.rs        the binary crate, also named billing
        └── bin/
            └── report.rs  another binary: cargo run --bin report
    

    A package has at most one library and any number of binaries. Each crate’s root file is the top of its module tree, so lib.rs declares the library’s modules with mod, and main.rs declares its own.

    In package.json terms, lib.rs is the code you expose through main or exports, and each binary is like an entry under bin:

    {
      "name": "billing",
      "exports": "./dist/index.js",
      "bin": { "billing": "./dist/cli.js" }
    }
    

    In .NET terms, a package with both is a class library and a console app in one, with no project reference to set up. In a .csproj, you choose one per project:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType> <!-- leave it out for a class library -->
        <TargetFramework>net10.0</TargetFramework>
      </PropertyGroup>
    </Project>
    

    When a package has both, main.rs uses the library like any other dependency, by the package name. Only items marked pub in lib.rs are visible to it:

    pub fn total(prices: &[u32]) -> u32 {
        prices.iter().sum()
    }
    fn main() {
        let total = billing::total(&[1000, 500]);
        println!("Total: {total} cents");
    }

    Output

    Total: 1500 cents

    (To run this example as a single file, its Run link adds the library as an inline mod billing.)

    Keeping main.rs thin and putting the logic in lib.rs is the usual layout for any program bigger than a script. Integration tests in tests/, benchmarks and other crates can only use a library, not a binary.

    Workspaces

    A workspace is several packages built together: one Cargo.lock and one target/ folder for all of them. Here’s a library shared by a command-line tool and a server:

    billing-app/
    ├── Cargo.toml              the workspace: [workspace], and no [package]
    ├── Cargo.lock              one lock file for every member
    ├── target/                 one build folder for every member
    └── crates/
        ├── billing/            a library (src/lib.rs)
        │   └── Cargo.toml
        ├── billing-cli/        a program (src/main.rs) that uses billing
        │   └── Cargo.toml
        └── billing-server/     a program (src/main.rs) that uses billing
            └── Cargo.toml
    

    The root Cargo.toml lists the members, and can share versions and settings with all of them:

    [workspace]
    members = ["crates/*"]
    resolver = "3"
    
    [workspace.package]
    version = "0.1.0"
    edition = "2024"
    
    [workspace.dependencies]
    billing = { path = "crates/billing" }
    serde = { version = "1", features = ["derive"] }
    

    Each member inherits what it needs with workspace = true:

    [package]
    name = "billing-cli"
    version.workspace = true
    edition.workspace = true
    
    [dependencies]
    billing.workspace = true
    serde.workspace = true
    

    resolver = "3" is the dependency resolver that edition 2024 packages use by default. A workspace root with no [package] has no edition to take it from, so you set it there.

    The pnpm version of the same setup is a pnpm-workspace.yaml and a workspace: dependency:

    packages:
      - "crates/*"
    
    {
      "name": "billing-cli",
      "dependencies": { "billing": "workspace:*" }
    }
    

    npm workspaces use a "workspaces" array in the root package.json instead. Either way you get one lock file at the root, as in Cargo. [workspace.dependencies] is like pnpm’s catalogs: one place to set a version that every member uses.

    The .NET version of the same setup is a solution file and project references. In .NET 10, dotnet new sln creates the XML-based BillingApp.slnx; older solutions use the .sln format, and the dotnet sln commands work with both:

    dotnet new sln -n BillingApp
    dotnet sln add src/Billing/Billing.csproj src/Billing.Cli/Billing.Cli.csproj
    dotnet add src/Billing.Cli/Billing.Cli.csproj reference src/Billing/Billing.csproj
    

    The project reference ends up in the .csproj as <ProjectReference Include="../Billing/Billing.csproj" />. [workspace.package] plays the part of Directory.Build.props, and [workspace.dependencies] the part of central package management (Directory.Packages.props). One difference: a solution mostly groups projects for building and the IDE, while a Cargo workspace also shares one lock file and one build folder.

    The commands work on the whole workspace or on one member:

    cargo build                          # every member (from the root)
    cargo run -p billing-cli -- --help   # one program: -p picks the package
    cargo test -p billing                # one member's tests
    cargo test --workspace               # every member's tests, from any folder
    cargo new crates/billing-report      # a new member, matched by crates/*
    

    Run inside a member’s folder, a plain cargo build or cargo test works on that member only. -p is pnpm’s --filter, and --workspace is -r.-p is like building one .csproj instead of the whole solution.

    Dependencies and versions

    A dependency comes from crates.io, a folder on disk or a git repository:

    [dependencies]
    serde = "1.0.200"                                  # crates.io: 1.0.200 or any later 1.x
    billing = { path = "../billing", version = "0.3" } # the folder locally; 0.3 from crates.io once published
    rules = { git = "https://example.com/rules.git", tag = "v2.1.0" }
    serde_json = { version = "1", optional = true }    # built only when a feature turns it on
    
    [dev-dependencies]
    pretty_assertions = "1"                            # tests, examples and benchmarks only
    
    [target.'cfg(windows)'.dependencies]
    windows-sys = "0.101"                              # only when building for Windows
    

    [dev-dependencies] is devDependencies.[dev-dependencies] is what you’d put in a separate test project’s .csproj: a dependency your code doesn’t ship with. A version is a range, not a pin: Cargo reads "1.0.200" as ^1.0.200. Versions follow semver, with one extra rule for 0.x:

    RequirementAllowsWhy
    "1.2.3" (same as "^1.2.3")1.2.3 up to, not including, 2.0.0A new major version may break your code.
    "0.4.1"0.4.1 up to, not including, 0.5.0Before 1.0, the minor version is the breaking one.
    "~1.2.3"1.2.3 up to, not including, 1.3.0Patch updates only.
    "=1.2.3"Exactly 1.2.3Rarely right in a library: it blocks every other crate from using a newer 1.2.x.
    These are the same rules as ^ and ~ in npm, with one trap: in package.json a bare "1.2.3" means exactly 1.2.3, while in Cargo.toml it means ^1.2.3. Caret is the default, so you don’t write it.
    This differs from NuGet, which reads Version="1.2.3" as “1.2.3 or higher” and restores the lowest match. Cargo picks the newest match, then records it in Cargo.lock.

    Features: optional parts of a crate

    A feature is a named switch in a library’s Cargo.toml. Users turn it on to get extra code, often code that needs an extra dependency:

    [dependencies]
    serde_json = { version = "1", optional = true }
    
    [features]
    default = []                  # features that are on unless a user opts out
    json = ["dep:serde_json"]     # turning on json also builds serde_json
    

    In the code, #[cfg(feature = "json")] keeps an item only when the feature is on. Without it, the item isn’t compiled, and neither is serde_json:

    pub struct Invoice {
        pub number: u32,
        pub total_cents: u32,
    }
    
    impl Invoice {
        #[cfg(feature = "json")]
        pub fn to_json(&self) -> String {
            serde_json::json!({ "number": self.number, "total": self.total_cents }).to_string()
        }
    }
    
    fn main() {
        let invoice = Invoice {
            number: 7,
            total_cents: 1500,
        };
        #[cfg(feature = "json")]
        println!("{}", invoice.to_json());
        #[cfg(not(feature = "json"))]
        println!("Invoice {}: {} cents", invoice.number, invoice.total_cents);
    }

    Output

    Invoice 7: 1500 cents

    This build has no json feature, so to_json doesn’t exist and the second println! runs. (This example is built without the Cargo.toml above, and Cargo warns about a feature = "…" name that the package doesn’t declare, a typo check called unexpected_cfgs. Its Run link carries a hidden #![allow(unexpected_cfgs)] line to silence that; in a real crate that declares json under [features], you don’t need it.) Users of the library pick features in their own Cargo.toml, or on the command line:

    [dependencies]
    billing = { path = "../billing", features = ["json"] }
    serde = { version = "1", default-features = false, features = ["derive"] } # derive, without the default std feature
    
    cargo build --features json        # turn on a feature of the package you're building
    cargo build --no-default-features  # turn off its default features
    cargo build --all-features         # turn on every feature, e.g. to check they all compile
    

    TypeScript has no equivalent. A library with optional parts usually ships them as separate packages (@billing/json) or subpath exports (billing/json), and relies on the bundler to drop what you don’t import. A Cargo feature goes further: code that’s switched off is never compiled, and its dependencies are never downloaded or built.

    C# has no equivalent across packages. Inside a project you can add a symbol with <DefineConstants> and test it with #if, but a NuGet package is compiled once by its author, so its users can’t switch parts of it on or off. Libraries ship optional parts as separate packages (Billing.Json) instead. A Cargo feature lets each user choose, because Cargo builds dependencies from source.

    Conditional compilation with cfg

    Features are one kind of cfg condition. Cargo and the compiler set others for every build:

    ConditionTrue when
    debug_assertionsA debug build (cargo build, cargo run); off with --release.
    testCompiling the crate’s own unit tests (cargo test).
    feature = "json"The json feature is on.
    windows, unix, target_os = "linux", target_os = "macos"Building for that operating system.
    target_arch = "x86_64", target_pointer_width = "64"Building for that processor or pointer size.

    Combine them with all(…), any(…) and not(…). You can test a condition in two ways:

    • #[cfg(…)] on an item, statement or field: when the condition is false, the code is removed before type checking, as if you’d never written it. This is C#‘s #if.
    • cfg!(…) in an expression: it becomes the constant true or false. Both branches stay in the code and must compile; the optimizer then drops the dead one.
    TypeScript
    build.ts
    const isDebug = process.env.NODE_ENV !== "production";
    const buildKind = isDebug ? "debug build" : "release build";
    console.log(buildKind);
    if (isDebug) {
      console.log("extra checks on");
    }
    C#
    Build.cs
    #if DEBUG
    var buildKind = "debug build";
    #else
    var buildKind = "release build";
    #endif
    Console.WriteLine(buildKind);
    #if DEBUG
    Console.WriteLine("extra checks on");
    #endif
    Rust
    #[cfg(debug_assertions)]
    fn build_kind() -> &'static str {
        "debug build"
    }
    
    #[cfg(not(debug_assertions))]
    fn build_kind() -> &'static str {
        "release build"
    }
    
    fn main() {
        println!("{}", build_kind());
        if cfg!(debug_assertions) {
            println!("extra checks on");
        }
    }

    Output

    debug build
    extra checks on

    process.env.NODE_ENV is read at run time. Bundlers such as Vite and webpack replace it with a constant in production builds and then remove the dead branch, which is the closest TypeScript gets to cfg.dotnet run and dotnet build use the Debug configuration, which defines DEBUG; -c Release doesn’t. Both Rust functions are named build_kind, which would normally be a duplicate definition. It compiles because exactly one of them exists in any build.

    Platform conditions work the same way. This prints a different folder depending on where it’s built:

    #[cfg(windows)]
    const CONFIG_DIR: &str = r"%APPDATA%\billing";
    
    #[cfg(not(windows))]
    const CONFIG_DIR: &str = "~/.config/billing";
    
    fn main() {
        println!("Config: {CONFIG_DIR}");
        println!("64-bit: {}", cfg!(target_pointer_width = "64"));
    }
    In Node you’d check process.platform at run time. In Rust, the other platform’s code isn’t in the binary at all.
    In C# you’d check OperatingSystem.IsWindows() at run time. In Rust, the other platform’s code isn’t in the binary at all.

    Which one should I use?

    Most code organization is modules. Reach for a new crate only when you have a reason: a second program, a part with its own dependencies, code other repositories use, or builds that are getting slow.

    WhatWhenWhyHow
    A moduleGrouping related code inside a crate. The default.No Cargo.toml changes, and privacy works at module level.mod invoice; and src/invoice.rs.
    lib.rs plus main.rsAny program bigger than a script.Tests in tests/ and other crates can use a library, not a binary. main.rs stays a thin wrapper.Add src/lib.rs; call it from main.rs as billing::run().
    src/bin/name.rsA second small program that uses the same library: a migration, an import tool.No new package or Cargo.toml.cargo run --bin name.
    A workspace memberSeveral programs share code, a part needs its own dependencies or features, or the crate takes too long to build.Each crate compiles separately and in parallel, and an unchanged crate isn’t rebuilt.List it in [workspace] members; depend on it with path or workspace = true.
    A published crateOther repositories depend on it, with their own release schedule.Users pick a version range, and semver tells them what’s safe to update.cargo publish to crates.io or a private registry, or a git dependency.
    A featureOptional parts of a library, especially ones that need extra dependencies.Users who don’t need it don’t download or compile it.[features] json = ["dep:serde_json"] and #[cfg(feature = "json")].
    #[cfg(…)] or cfg!(…)Code for one platform, debug builds only, or tests only.#[cfg] removes the code; cfg! keeps both branches type-checked.#[cfg(windows)], #[cfg(test)], if cfg!(debug_assertions).
    Module, crate or workspace member?
    1. Do other repositories depend on it, on their own release schedule?

      Yes

      Its own package, published to crates.io or a private registryOr a workspace member that you publish. Give it a semver version and keep its public API small.

      No
    2. Do several programs in this repository share it, or does it need its own dependencies or features?

      Yes

      A workspace member: a library package next to the programsDepend on it with billing.workspace = true or a path.

      No
    3. Is it a second, small program that uses the same code?

      Yes

      A file in src/bin/It can use everything pub in src/lib.rs.

      No
    4. Otherwise: A module in the crate you have: mod name; and a file. You can move it into its own crate later, when one of these answers becomes yes.

    Rule of thumb: start with one package, lib.rs for the logic and a thin main.rs, and organize it with modules. Make it a workspace when a second program or a slow build gives you a reason. Add a feature only for optional parts of a library, and use cfg for code that depends on the platform or build, not on your users’ choices.

    Under the hood

    What cargo build does in a workspace:

    1. One dependency graph. Cargo resolves every member’s dependencies together and records the result in the one Cargo.lock at the root. Semver-compatible requirements share one version: if two members ask for serde = "1.0.180" and serde = "1.0.200", both get the same 1.x. Incompatible ones, such as 0.4 and 0.5, can both end up in the build as separate crates.
    2. Features are unified. A dependency is built with the union of the features that everything in the build asked for. If you build two members together and one turns on billing/json, both get billing with json.
    3. One crate, one compilation. rustc compiles each crate as a unit, crates that don’t depend on each other in parallel. Changing a file recompiles its crate and the crates that depend on it, and nothing else. Splitting a big crate into a few members is a common way to speed up builds.
    4. One target/. Every member’s output goes to the root’s target/, so dependencies are compiled once for the whole workspace.

    cargo tree shows the resolved graph: cargo tree -i serde shows who depends on serde, cargo tree -d lists crates that appear in more than one version, and cargo tree -e features shows which features are on. It’s the npm ls or pnpm why of Cargo.It’s like dotnet list package --include-transitive, with the whole graph.

    Cargo.lock for programs and libraries

    Cargo.lock only matters at the top: when your crate is a dependency of something else, Cargo ignores your lock file and resolves your version ranges again for that build. So:

    • Programs (and workspaces): commit Cargo.lock. It makes every build, on every machine and in CI, use the same versions.
    • Libraries: Cargo’s advice is to commit it too, for reproducible CI, but your users never see it. They get whatever versions your ranges allow, so your ranges must be honest: if you use something added in 1.0.200, write "1.0.200", not "1".
    npm behaves the same way: a dependency’s package-lock.json is ignored when you install it.
    NuGet’s packages.lock.json, which you opt into with <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>, works the same way: it locks your own project’s restore, not the projects that reference your package. Cargo writes Cargo.lock on every build, with no opt-in.

    Common pitfalls

    Common pitfallHyphens in package names become underscores in code

    A package named billing-core is the crate billing_core in Rust code: use billing_core::Invoice;. In Cargo.toml you still write billing-core. Rust identifiers can’t contain -, so Cargo converts the name for you.

    Common pitfallFeatures must only add

    Because features are unified, any crate in the build can turn on a feature of your library for everyone. So a feature must only add code, never remove or change it. A no_std or without_logging feature breaks the crates that expect std or logging. Turn it around: make std a default feature that users can switch off with default-features = false.

    Common pitfallcfg(test) code is only for the crate's own unit tests

    #[cfg(test)] is set when cargo test compiles a crate’s unit tests, the mod tests blocks. Integration tests in tests/ use the library like any other caller, built without cfg(test), so they can’t see helpers behind it, and neither can other crates. Put shared test helpers in tests/common/mod.rs, or behind a feature such as test-utils.

    Common pitfallcfg! doesn't remove code

    if cfg!(windows) { … } still compiles the branch on every platform. If the branch calls a function that only exists under #[cfg(windows)], the build fails everywhere else. Put #[cfg(windows)] on the statement, block or function instead, so the code is removed.

    Common pitfallProfiles belong to the workspace root

    [profile.release] in a member’s Cargo.toml is ignored, with a warning. Build settings such as opt-level and lto apply to the whole build, so they go in the root Cargo.toml.

    Try it yourself

    Exercise: port this to Rust

    Port this program. It prints a debug message in debug builds only, and the release build shouldn’t contain the message at all. Run it with cargo run, then with cargo run --release.

    Starting code in TypeScript
    log.ts
    const isDebug = process.env.NODE_ENV !== "production";
    
    function log(message: string): void {
      if (isDebug) {
        console.log(`[debug] ${message}`);
      }
    }
    
    log("loading config");
    console.log("ready");
    Starting code in C#
    Log.cs
    using System.Diagnostics;
    
    Log("loading config");
    Console.WriteLine("ready");
    
    [Conditional("DEBUG")]
    static void Log(string message) => Console.WriteLine($"[debug] {message}");

    Expected output

    [debug] loading config
    ready
    Show a hint

    Put #[cfg(debug_assertions)] on a log function that prints, and #[cfg(not(debug_assertions))] on an empty one with the same signature. Name the unused parameter _message in the empty version.

    Show a solution
    #[cfg(debug_assertions)]
    fn log(message: &str) {
        println!("[debug] {message}");
    }
    
    #[cfg(not(debug_assertions))]
    fn log(_message: &str) {}
    
    fn main() {
        log("loading config");
        println!("ready");
    }

    In a debug build, log prints. In a release build, the empty version is compiled instead, and the optimizer removes the calls to it, so release builds pay nothing. Run cargo run --release and only ready is printed. if cfg!(debug_assertions) inside a single function would also work.