codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

58 / 58 topics
39Cargo40Build System40Cargo Features
Tutorials/Rust/Cargo Features
🦀Rust

Cargo Features

Updated 2026-05-15
10 min read

Cargo Features

Introduction

In the world of Rust, package management is handled by Cargo, which is a powerful tool that simplifies building, testing, and managing dependencies for your projects. One of the advanced features provided by Cargo is the ability to conditionally compile code based on specific "features". This feature allows developers to include or exclude certain parts of their code depending on whether those features are enabled.

Features can be used to add optional functionality to a crate without increasing its binary size unless the user explicitly requests it. This is particularly useful for libraries that want to support multiple optional extensions or integrations.

Concept

A feature in Cargo is essentially a named flag that can be enabled or disabled when compiling a crate. Features are defined in the Cargo.toml file of a Rust project and can be used to control which parts of the code are compiled.

When you enable a feature, all the code associated with that feature will be included in the final binary. Conversely, if a feature is not enabled, the corresponding code will be excluded from compilation.

Key Points

  • Feature Definition: Features are defined under the [features] section in Cargo.toml.
  • Default Features: By default, Cargo compiles all features unless explicitly disabled.
  • Dependency Features: You can specify which features of a dependency should be enabled when using that dependency.

Examples

Let's walk through some practical examples to illustrate how features work in Rust projects.

Example 1: Basic Feature Usage

Suppose you have a library crate called my_library that provides optional logging functionality. You want to allow users to enable or disable this logging feature.

Step 1: Define the Feature in Cargo.toml

[package]
name = "my_library"
version = "0.1.0"
edition = "2018"

[features]
default = []
logging = []

In this example, we define a single feature called logging. The default feature is empty, meaning no features are enabled by default.

Step 2: Use the Feature in Your Code

#[cfg(feature = "logging")]
fn log(message: &str) {
    println!("Log: {}", message);
}

#[cfg(not(feature = "logging"))]
fn log(_message: &str) {
    // Do nothing if logging is not enabled
}

Here, we use the `#[cfg]` attribute to conditionally compile the `log` function based on whether the `logging` feature is enabled. If the feature is enabled, the function prints the message; otherwise, it does nothing.

#### Step 3: Compile with and without the Feature

To compile the crate with the logging feature enabled:

<Terminal>
{`$ cargo build --features logging`}

To compile the crate without the logging feature (default behavior):

{`$ cargo build`}
</Terminal>

### Example 2: Dependency Features

Now, let's consider a scenario where your library depends on another crate that provides optional features. You want to enable these features conditionally based on your own crate's features.

#### Step 1: Define the Feature in `Cargo.toml`

```toml
[package]
name = "my_library"
version = "0.1.0"
edition = "2018"

[features]
default = []
extra_features = ["dep_crate/feature_a"]

In this example, we define a feature called extra_features that enables feature_a of the dependency crate dep_crate.

Step 2: Specify Dependencies

[dependencies]
dep_crate = { version = "1.0", default-features = false }

We specify `default-features = false` to disable all default features of `dep_crate`. This ensures that only the explicitly enabled features are used.

#### Step 3: Use the Feature in Your Code

```rust
#[cfg(feature = "extra_features")]
fn use_extra_functionality() {
    dep_crate::feature_a();
}

#[cfg(not(feature = "extra_features"))]
fn use_extra_functionality() {
    // Fallback or alternative functionality
}

Here, we conditionally call a function from `dep_crate` based on whether the `extra_features` feature is enabled.

#### Step 4: Compile with and without the Feature

To compile the crate with the extra features enabled:

<Terminal>
{`$ cargo build --features extra_features`}

To compile the crate without the extra features (default behavior):

{`$ cargo build`}
</Terminal>

### Example 3: Conditional Compilation in Binaries

Features can also be used to conditionally compile different parts of a binary application.

#### Step 1: Define the Feature in `Cargo.toml`

```toml
[package]
name = "my_app"
version = "0.1.0"
edition = "2018"

[features]
default = []
gui = []

In this example, we define a feature called gui that enables graphical user interface components.

Step 2: Use the Feature in Your Code

#[cfg(feature = "gui")]
fn main() {
    println!("Running GUI version");
    // Initialize and run GUI code
}

#[cfg(not(feature = "gui"))]
fn main() {
    println!("Running CLI version");
    // Initialize and run command-line interface code
}

Here, we use the #[cfg] attribute to conditionally compile different versions of the main function based on whether the gui feature is enabled.

Step 3: Compile with and without the Feature

To compile the application with the GUI feature enabled:

Terminal

Conclusion

Cargo features provide a powerful way to conditionally compile code in Rust projects. By defining and using features, you can create flexible libraries and applications that support optional functionality without bloating the final binary size. This makes it easier to manage complex dependencies and tailor your project's behavior to specific needs.

Remember to always define features clearly in Cargo.toml and use the #[cfg] attribute appropriately in your code to take full advantage of this feature.


PreviousSecurity

Recommended Gear

Security