features 特性标志
核心概念
Features(特性标志)是 Cargo 提供的条件编译机制,允许 crate 作者将功能拆分为可选模块,让使用者按需启用。通过 features,一个 crate 可以在不增加所有用户编译负担的前提下提供丰富的功能。例如 serde 的 derive feature 控制是否启用派生宏,tokio 的 full feature 一次启用所有子模块。
Features 在 Cargo.toml 的 [features] 段定义,每个 feature 是一个名称到依赖列表的映射。启用一个 feature 会自动启用它依赖的其他 feature 和可选依赖。Features 是可叠加的(additive)——启用一个 feature 不应该禁用其他功能。
[features]
# 默认启用的 feature
default = ["json"]
# 自定义 feature
json = ["dep:serde", "dep:serde_json"]
yaml = ["dep:serde_yaml"]
full = ["json", "yaml", "async"]
async = ["dep:tokio"]
[dependencies]
serde = { version = "1", optional = true }
serde_json = { version = "1", optional = true }
serde_yaml = { version = "0.9", optional = true }
tokio = { version = "1", optional = true, features = ["full"] }定义 Features
[features]
# === 基本定义 ===
# feature_name = [依赖列表]
# 空 feature(纯条件编译标志)
unstable = []
# 启用可选依赖
json = ["dep:serde", "dep:serde_json"]
# 启用其他 feature
full = ["json", "yaml", "async"]
# 启用依赖的 feature
with-serde = ["my-types/serde"]
# 表示启用 my-types crate 的 serde feature
# === default feature ===
# 使用者不指定 features 时默认启用
default = ["json"]
# === dep: 前缀(Rust 1.60+)===
# 明确表示启用的是可选依赖而非同名 feature
json = ["dep:serde_json"]
# 旧写法(隐式创建同名 feature):
# json = ["serde_json"]使用 Features
# === 使用者侧的 Cargo.toml ===
[dependencies]
# 使用默认 features
my-lib = "1.0"
# 禁用默认 features
my-lib = { version = "1.0", default-features = false }
# 禁用默认并启用指定 features
my-lib = { version = "1.0", default-features = false, features = ["json", "async"] }
# 启用额外 features(默认的也保留)
my-lib = { version = "1.0", features = ["yaml"] }# 命令行控制 features
# cargo build --features "json yaml"
# cargo build --no-default-features
# cargo build --no-default-features --features "json"
# cargo build --all-features条件编译
// 在代码中根据 feature 条件编译
// === 条件编译模块 ===
#[cfg(feature = "json")]
pub mod json {
// 只有启用 json feature 时才编译这个模块
pub fn parse(s: &str) -> Result<serde_json::Value, serde_json::Error> {
serde_json::from_str(s)
}
}
#[cfg(feature = "async")]
pub mod async_api {
// 只有启用 async feature 时才编译
pub async fn fetch(url: &str) -> String {
// ...
format!("fetched {}", url)
}
}
// === 条件编译函数 ===
#[cfg(feature = "json")]
pub fn to_json<T: serde::Serialize>(value: &T) -> String {
serde_json::to_string(value).unwrap()
}
// === 条件编译 trait 实现 ===
pub struct MyType {
pub data: String,
}
#[cfg(feature = "json")]
impl serde::Serialize for MyType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.data.serialize(serializer)
}
}
// === 条件导入 ===
#[cfg(feature = "json")]
use serde_json;
fn main() {
println!("features 通过 #[cfg(feature = \"name\")] 控制条件编译");
}基本示例
# 一个实际库的 feature 配置
[package]
name = "my-http"
version = "0.1.0"
edition = "2024"
[features]
default = ["json", "gzip"]
json = ["dep:serde", "dep:serde_json"]
gzip = ["dep:flate2"]
tls = ["dep:rustls"]
full = ["json", "gzip", "tls"]
[dependencies]
serde = { version = "1", optional = true, features = ["derive"] }
serde_json = { version = "1", optional = true }
flate2 = { version = "1", optional = true }
rustls = { version = "0.23", optional = true }// src/lib.rs
pub struct Response {
pub status: u16,
pub body: Vec<u8>,
}
impl Response {
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).to_string()
}
// 只有启用 json feature 时才有这个方法
#[cfg(feature = "json")]
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
serde_json::from_slice(&self.body)
}
// 只有启用 gzip feature 时才有这个方法
#[cfg(feature = "gzip")]
pub fn decompress(&self) -> Result<Vec<u8>, std::io::Error> {
use flate2::read::GzDecoder;
use std::io::Read;
let mut decoder = GzDecoder::new(&self.body[..]);
let mut result = Vec::new();
decoder.read_to_end(&mut result)?;
Ok(result)
}
}
fn main() {
let resp = Response {
status: 200,
body: b"hello".to_vec(),
};
println!("text: {}", resp.text());
}常见问题
问题一:features 是可叠加的是什么意思?
启用一个 feature 只应该增加功能,不应该改变或禁用已有功能。Cargo 在解析依赖时会合并所有使用者请求的 features,如果 feature A 和 B 互相冲突,会导致不可预料的行为。
问题二:dep: 前缀和直接写依赖名有什么区别?
直接写 json = ["serde_json"] 会隐式为 serde_json 创建一个同名 feature。用 dep:serde_json 则明确表示启用可选依赖,不会创建同名 feature。Rust 1.60+ 推荐使用 dep: 前缀。
问题三:怎么知道一个 crate 有哪些 features?
查看 crate 的 Cargo.toml 或 docs.rs 上的文档。docs.rs 会在文档中标注每个功能需要哪个 feature。也可以用 cargo add crate_name --features 查看。
问题四:多个依赖者启用不同 features 会怎样?
Cargo 会合并(union)所有请求的 features。如果 crate A 依赖 my-lib 启用 json,crate B 依赖 my-lib 启用 yaml,最终 my-lib 会同时启用 json 和 yaml。
适用场景
- 可选功能模块:序列化、压缩、TLS 等
- 可选依赖控制:减小不需要的依赖
- 平台特定代码:Windows/Linux 专用功能
- 不稳定 API 标记:用
unstablefeature 隔离实验性 API
注意事项
- Features 必须是可叠加的,不能互斥
- 使用
dep:前缀(1.60+)避免隐式 feature 创建 default-features = false禁用默认 features- Features 在整个依赖树中会被合并
- 不要在 feature 中做破坏性改变
--all-features可以测试所有 feature 组合
总结
Features 是 Cargo 的条件编译机制,允许 crate 按需提供可选功能。在 [features] 段定义 feature 名称和依赖关系,default 指定默认启用的 features。使用者通过 features = [...] 启用、default-features = false 禁用默认 features。代码中用 #[cfg(feature = "name")] 条件编译。dep: 前缀(1.60+)明确引用可选依赖。Features 是可叠加的,Cargo 会合并依赖树中所有请求的 features。合理的 feature 设计能让库既功能丰富又保持轻量。