Rust

Lesson 09

Cargo feature dependencies

Keep optional dependencies behind named features so builds include only the integrations they need.

Good Code

src/lib.rs
#[cfg(feature = "postgres")]
pub mod postgres_store;

pub fn storage_name() -> &'static str {
    // Feature-gated code keeps the default build small and intentional.
    #[cfg(feature = "postgres")]
    {
        return "postgres";
    }

    "memory"
}

Bad Code

lib.rs
pub mod postgres_store;
pub mod redis_store;

pub fn storage_name() -> &'static str {
    // Every integration is compiled even when the app uses only memory storage.
    "postgres"
}

Review Notes

What to review

Good Code

The good version gates the optional store behind a named feature. A default build avoids pulling in database code unless the package enables that integration.

Bad Code

The bad version always compiles every store module. Optional infrastructure becomes a hidden dependency for simple builds, tests, and local tools.

Takeaways

  • A Rust crate should make optional integrations explicit through Cargo features and guarded code paths.