默认特性 default-features ​

核心概念 ​

default feature 是 Cargo 中一个特殊的 feature 名称,定义了当使用者不显式指定 features 时默认启用的功能集合。库作者通过 default = [...] 列出最常用的 features,让大多数用户开箱即用。使用者可以通过 default-features = false 禁用默认 features,然后按需启用所需的功能。

这个机制让库能同时满足两类用户:普通用户直接使用默认配置,有特殊需求的用户(如嵌入式开发、最小化依赖)可以精确控制启用哪些功能。

toml
# === 库作者侧 ===
[features]
default = ["std", "json"]     # 默认启用 std 和 json
std = []                       # 标准库支持
json = ["dep:serde_json"]     # JSON 支持
no_std_compat = []             # no_std 兼容

# === 使用者侧 ===
[dependencies]
# 使用默认 features(等同于启用 std + json)
my-lib = "1.0"

# 禁用默认 features
my-lib = { version = "1.0", default-features = false }

# 禁用默认,只启用需要的
my-lib = { version = "1.0", default-features = false, features = ["json"] }

设计 default features ​

toml
# 好的 default 设计:包含最常用的功能

# 示例:一个 HTTP 客户端库
[features]
default = ["json", "gzip", "rustls-tls"]

# 序列化支持
json = ["dep:serde", "dep:serde_json"]

# 压缩
gzip = ["dep:flate2"]
brotli = ["dep:brotli"]

# TLS 后端(二选一,但 default 只选一个)
rustls-tls = ["dep:rustls"]
native-tls = ["dep:native-tls"]

# 全部功能
full = ["json", "gzip", "brotli", "rustls-tls"]

# no_std 支持(需要禁用 default)
no_std = []
rust
// 库代码中根据 default features 条件编译

// std feature 通常用于 no_std 兼容
#[cfg(feature = "std")]
use std::collections::HashMap;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap;

// json feature
#[cfg(feature = "json")]
pub fn parse_json(s: &str) -> Result<serde_json::Value, serde_json::Error> {
    serde_json::from_str(s)
}

fn main() {
    println!("default features 提供开箱即用的体验");
}

使用者控制 default features ​

toml
# === 完全使用默认 ===
[dependencies]
tokio = "1"
# 等同于:tokio = { version = "1", default-features = true }
# tokio 的 default 是空的,所以实际没启用额外功能

# === 禁用默认,手动选择 ===
[dependencies]
tokio = { version = "1", default-features = false, features = ["rt", "macros"] }
# 只启用运行时和宏,不启用 tokio 默认的所有功能

# === 保留默认,额外启用 ===
[dependencies]
serde = { version = "1", features = ["derive"] }
# 保留 serde 的默认 features,额外启用 derive

# === 常见的 no_std 用法 ===
[dependencies]
my-lib = { version = "1.0", default-features = false, features = ["no_std"] }

default-features 在依赖树中的行为 ​

toml
# 重要:default-features = false 只影响你自己对该 crate 的请求
# 如果依赖树中其他 crate 也依赖同一个 crate 且没有禁用 default,
# 那么 default features 仍然会被启用

# 你的 Cargo.toml
[dependencies]
serde = { version = "1", default-features = false }    # 你禁用了 default
some-lib = "1.0"                                        # some-lib 依赖 serde 且启用 default

# 结果:serde 的 default features 仍然被启用
# 因为 Cargo 会合并所有使用者的 feature 请求
场景结果
你禁用 default,无其他依赖者default 被禁用
你禁用 default,其他依赖者启用default 被启用(合并)
你启用 defaultdefault 被启用

基本示例 ​

toml
# 实际项目中的 default-features 使用

[package]
name = "embedded-app"
version = "0.1.0"
edition = "2024"

[dependencies]
# 嵌入式场景:禁用 std 相关的默认功能
serde = { version = "1", default-features = false, features = ["derive", "alloc"] }

# 精简的 tokio:只用单线程运行时
tokio = { version = "1", default-features = false, features = ["rt", "macros"] }

# 保留默认功能
log = "0.4"       # default features 保留
rust
// 根据 default features 编写兼容代码

pub struct Config {
    pub name: String,
    pub value: i32,
}

impl Config {
    pub fn new(name: &str, value: i32) -> Self {
        Config {
            name: name.to_string(),
            value,
        }
    }
}

fn main() {
    let config = Config::new("test", 42);
    println!("{}: {}", config.name, config.value);
}

常见问题 ​

问题一:default-features = false 和不写 features 有什么区别?

不写 features 等同于 default-features = true,会启用 crate 定义的所有默认功能。default-features = false 则完全不启用默认功能,从零开始按需启用。

问题二:为什么我禁用了 default 但功能还是启用了?

因为依赖树中其他 crate 可能也依赖同一个 crate 且没有禁用 default。Cargo 会合并所有 feature 请求,只要有一个依赖者启用了 default,它就会被启用。

问题三:库应该把什么放在 default 里?

放最常用的、大多数用户都需要的功能。不要把重量级的依赖放在 default 里(如数据库驱动、TLS 实现),除非它们确实是核心功能。std feature 通常放在 default 里。

问题四:default 可以为空吗?

可以。default = [] 表示默认不启用任何额外功能。tokio 就是这样做的——用户必须显式选择需要的组件。

适用场景 ​

  • no_std 库:通过 default = ["std"] 让 std 用户开箱即用
  • 精简编译:禁用不需要的功能减小二进制大小
  • 嵌入式开发:default-features = false 去除标准库依赖
  • 最小化依赖树:只启用需要的可选依赖

注意事项 ​

  • default-features = false 只影响你自己的 feature 请求
  • 依赖树中的 feature 合并可能导致 default 仍然被启用
  • 库作者应将最常用的功能放在 default 中
  • default = [] 是合法的,表示无默认功能
  • 命令行 --no-default-features 可以全局禁用默认 features
  • features 是可叠加的,禁用 default 不会导致功能丧失(除非代码依赖它)

总结 ​

default feature 定义了 crate 在使用者不指定 features 时默认启用的功能集合。使用者通过 default-features = false 禁用默认功能,再用 features = [...] 按需启用。default features 在依赖树中会被合并——如果任何依赖者启用了 default,它就会生效。库作者应将最常用的功能放在 default 中,重量级或可选的功能不要放。default = [] 表示无默认功能,适合需要用户显式选择组件的场景(如 tokio)。