features 与依赖管理

上一节练习答案要点

上一节练习给 core 补 top 函数,一行就够:max_by_key 在空迭代器上自动返回 None(分数相同时返回最后出现的那个)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
mod core {
    #[derive(Debug, Clone)]
    pub struct User {
        pub name: String,
        pub score: u32,
    }
    impl User {
        pub fn new(name: &str, score: u32) -> Self {
            User { name: name.to_string(), score }
        }
        pub fn level(&self) -> &'static str {
            if self.score >= 90 { "优秀" } else if self.score >= 60 { "及格" } else { "待提高" }
        }
    }
    pub fn average(users: &[User]) -> f64 {
        if users.is_empty() { return 0.0; }
        users.iter().map(|u| u.score as f64).sum::<f64>() / users.len() as f64
    }
    pub fn top(users: &[User]) -> Option<&User> {
        users.iter().max_by_key(|u| u.score)
    }
}

fn main() {
    let users = vec![
        core::User::new("小明", 92),
        core::User::new("小红", 78),
        core::User::new("小刚", 55),
    ];
    for u in &users {
        println!("{}:{} 分({})", u.name, u.score, u.level());
    }
    println!("平均分:{:.1}", core::average(&users));
    if let Some(best) = core::top(&users) {
        println!("最高分:{}({} 分)", best.name, best.score);
    }
    println!("空切片的 top:{:?}", core::top(&[]));
}

输出:

1
2
3
4
5
6
小明:92 分(优秀)
小红:78 分(及格)
小刚:55 分(待提高)
平均分:75.0
最高分:小明(92 分)
空切片的 top:None

思考题要点:

  1. use core::User; 里的 core 是 crate 名(包名默认即库 crate 名)。包名改成 score-core 后,依赖写 score-core = { path = "../core" },代码写 use score_core::User;;也可重命名:core = { package = "score-core", path = "../core" }。
  2. 合并回一个包:少一份清单、重构不用考虑包边界;代价是依赖混在一起、无法单独发布 core。判断标准:会被别处复用、或依赖明显不同,就拆开;只服务于这一个程序,就合并。
  3. 工作空间只有一份 Cargo.lock,Cargo 选同时满足所有需求的版本:core 写 "1.0.200"、app 写 "1.0.210",最终共用 1.0.210 或更高兼容版。本节讲透这套规则。

本节讲依赖怎么声明、版本怎么选、可选功能怎么用 features 控制。

学习目标

读完本节,你会:理解 ^、~、= 等版本需求允许哪些版本;分清 Cargo.toml 的需求与 Cargo.lock 的锁定;用可选依赖加 features 做可选功能(default、dep:、default-features = false);用 #[cfg(...)] 与 cfg! 做条件编译并分清两者;理解 feature 统一与 resolver 2;会用 cargo add、cargo update、cargo tree 管理依赖。

核心概念

版本需求不是版本号

[dependencies] 里一行引入一个外部包:

1
2
[dependencies]
serde = { version = "1.0", features = ["derive"] }

"1.0" 不是恰好 1.0,而是版本需求 >=1.0.0, <2.0.0。Cargo 默认用插入符(caret)语义:允许不改变最左边非零数字的升级。

  • "^1.2.3":>=1.2.3, <2.0.0,主版本不变即可升级。
  • "^0.2.3":>=0.2.3, <0.3.0。0.x 阶段次版本升级就可能不兼容,所以把次版本当主版本看。
  • "^0.0.3":>=0.0.3, <0.0.4,等于精确锁定。
  • "~1.2.3":>=1.2.3, <1.3.0,只允许修订号升级。
  • "=1.2.3":精确等于,一般只在排查问题时临时用。

生态遵循语义化版本(主版本不变承诺兼容),所以 "1.0" 表示“1.x 最新版都行”:修复版自动受益,2.0 不会被擅自引入。依赖来源还有 path(本地目录)和 git(仓库,可带 branch/tag/rev)。

Cargo.lock:需求变成实际选择

版本需求决定候选集,Cargo.lock 记录实际选定的精确版本。首次构建解析出满足全部需求的最新组合并写入锁文件,之后沿用,保证各机器构建一致。

两个实务结论:二进制项目提交 Cargo.lock,保证部署可复现;库项目通常不必提交,因为库的版本由使用它的二进制项目决定。升级用 cargo update(全部)或 cargo update -p serde(单个),升级后跑测试再提交新锁文件。

features:编译期可选开关

包在 [features] 里定义命名开关。每个 feature 可以打开其他 feature、可选依赖,或某个依赖的 feature:

1
2
3
4
5
6
7
[dependencies]
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }

[features]
default = ["json"]
json = ["dep:serde", "dep:serde_json"]

三条规则:

  1. 可选依赖(optional = true)默认不参与编译,feature 用 dep:serde 显式启用。旧写法 json = ["serde"] 会把依赖名暴露成公开 feature;dep: 把“依赖”与“功能名”分开。
  2. default 是默认打开的一组 feature。依赖方写 default-features = false、或构建当前包时加 --no-default-features 可以关掉。关掉后包仍必须能编译,所以核心代码不能假设 default 永远开着。
  3. feature 只能叠加,不能互斥:你无法阻止下游同时打开 A 和 B,任意组合都必须能编译。“二选一”用运行时配置。

打开方式:依赖声明写 features = ["json"];构建自己的包用 cargo build --features json 或 cargo test --all-features(CI 验证全部组合)。

条件编译:cfg 把开关接到代码上

1
2
3
4
5
6
#[cfg(feature = "json")]
pub mod json_support;   // 关着时整段不参与编译

pub fn describe() -> &'static str {
    if cfg!(feature = "json") { "json 已启用" } else { "json 未启用" }
}
  • #[cfg(...)] 是属性:条件不成立时,被标记的模块、函数、字段在类型检查前就被移除,所以能守住引用可选依赖的代码。
  • cfg!(...) 是宏,展开成布尔字面量:两个分支都要编译、都要类型正确。它适合便宜的布尔分叉,不能守住引用可选依赖的代码。

条件可组合:all(...)、any(...)、not(...)。feature 名拼错时新版 rustc 会报 unexpected cfg condition 警告,看到先核对拼写。

feature 统一与 resolver 2

Cargo 对每个依赖只编译一份,feature 取所有请求方的并集:你只要 tokio 的 rt、别人要求 full,你的构建里 tokio 也是 full。这保证行为一致、只编一次,代价是你关掉的功能可能被别人打开。

resolver 2(Edition 2021 起默认)在三处不再统一:平台专属依赖的 feature 不污染其他平台;[dev-dependencies] 的 feature 只在测试时生效(所以 cargo build 与 cargo test 可能用不同 feature 集、切换要重编,属正常);[build-dependencies] 与过程宏的 feature 分开解析。

排查“谁打开了这个 feature”用 cargo tree -e features -i tokio;查重复版本用 cargo tree -d。

依赖种类与日常命令

  • [dependencies]:正常依赖。[dev-dependencies]:只在测试、示例、基准里用,不进发布产物。[build-dependencies]:build.rs 构建脚本用。[target.'cfg(windows)'.dependencies]:按平台引入,条件写 cfg 表达式。

日常命令:cargo add serde --features derive 写依赖并选版本,cargo remove 删除,cargo update 升级锁文件,cargo tree 看依赖树。手写 Cargo.toml 也完全可以。

可运行代码

在线沙箱是单文件、无外部 crate,下面用模拟把规则跑给你看,语义与真实 Cargo 一致,每个示例附本地复现方法。

示例 1:版本需求匹配

把插入符、波浪符写成函数,验证 "1.0" 为什么能接受 1.0.210、不能接受 2.0.0。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Version(u32, u32, u32);

fn parse(s: &str) -> Version {
    let p: Vec<u32> = s.split('.').map(|x| x.parse().unwrap_or(0)).collect();
    Version(p[0], *p.get(1).unwrap_or(&0), *p.get(2).unwrap_or(&0))
}

fn caret_ok(req: &str, v: Version) -> bool {
    let r = parse(req);
    if v < r { return false; }
    if r.0 > 0 { v.0 == r.0 }
    else if r.1 > 0 { v.0 == 0 && v.1 == r.1 }
    else { v == r }
}

fn tilde_ok(req: &str, v: Version) -> bool {
    let r = parse(req);
    v >= r && v.0 == r.0 && v.1 == r.1
}

fn main() {
    let cases = [
        ("^1.2.3", "1.9.0", true), ("^1.2.3", "2.0.0", false),
        ("^1.2.3", "1.2.2", false), ("^0.2.3", "0.2.9", true),
        ("^0.2.3", "0.3.0", false), ("^0.0.3", "0.0.3", true),
        ("^0.0.3", "0.0.4", false), ("~1.2.3", "1.2.9", true),
        ("~1.2.3", "1.3.0", false),
    ];
    for (req, cand, want) in cases {
        let got = if req.starts_with('~') {
            tilde_ok(&req[1..], parse(cand))
        } else {
            caret_ok(&req[1..], parse(cand))
        };
        println!("{} 接受 {}?{}(期望 {}){}", req, cand, got, want,
                 if got == want { "✓" } else { "✗" });
    }
}

输出:

1
2
3
4
5
6
7
8
9
^1.2.3 接受 1.9.0?true(期望 true)✓
^1.2.3 接受 2.0.0?false(期望 false)✓
^1.2.3 接受 1.2.2?false(期望 false)✓
^0.2.3 接受 0.2.9?true(期望 true)✓
^0.2.3 接受 0.3.0?false(期望 false)✓
^0.0.3 接受 0.0.3?true(期望 true)✓
^0.0.3 接受 0.0.4?false(期望 false)✓
~1.2.3 接受 1.2.9?true(期望 true)✓
~1.2.3 接受 1.3.0?false(期望 false)✓

本地复现:serde = "1.0" 构建后看 Cargo.lock 的实际版本;改 "=1.0.200" 再构建,锁文件精确停在 1.0.200。

示例 2:cfg! 与条件编译

沙箱没有 Cargo feature,但 cfg 对平台、构建类型等条件同样生效,机制一致。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#[cfg(debug_assertions)]
fn build_kind() -> &'static str { "debug 构建(断言开启)" }

#[cfg(not(debug_assertions))]
fn build_kind() -> &'static str { "release 构建" }

#[cfg(feature = "json")]
fn json_state() -> &'static str { "json feature 已启用" }

#[cfg(not(feature = "json"))]
fn json_state() -> &'static str { "json feature 未启用(沙箱里没有 Cargo feature,走这一支)" }

fn main() {
    println!("{}", build_kind());
    println!("{}", json_state());
    // cfg! 展开成布尔值,两个分支都会被编译检查
    let hint = if cfg!(target_os = "linux") {
        "运行在 Linux 上"
    } else if cfg!(target_os = "macos") {
        "运行在 macOS 上"
    } else {
        "运行在其他系统上"
    };
    println!("{}", hint);
    let combo = cfg!(all(unix, not(target_os = "macos")));
    println!("是 Unix 且不是 macOS?{}", combo);
}

输出(在线运行器按 release 构建;本地 cargo run 的 debug 构建第一行会显示 debug):

1
2
3
4
release 构建
json feature 未启用(沙箱里没有 Cargo feature,走这一支)
运行在 Linux 上
是 Unix 且不是 macOS?true

本地复现:[features] 加 json = [],把两支搬进 main.rs,对比 cargo run 与 cargo run --features json;再故意拼错名字看警告。

示例 3:可选依赖与 default

模拟一个库:核心功能永远可用,json 可选且默认打开,关掉后核心照样工作。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
mod mylib {
    pub struct Record {
        pub name: String,
        pub score: u32,
    }
    pub fn summary(r: &Record) -> String {
        format!("{}:{} 分", r.name, r.score)
    }
    // 真实项目里这段被 #[cfg(feature = "json")] 守住,并通过 dep:serde_json 启用可选依赖
    pub fn to_json(r: &Record) -> String {
        format!("{{\"name\":\"{}\",\"score\":{}}}", r.name, r.score)
    }
}

fn main() {
    let builds = [
        ("默认构建(default 含 json)", true),
        ("--no-default-features", false),
        ("--no-default-features --features json", true),
    ];
    let r = mylib::Record { name: "小明".to_string(), score: 92 };
    for (label, json_on) in builds {
        println!("--- {} ---", label);
        println!("核心功能:{}", mylib::summary(&r));
        if json_on {
            println!("可选功能:{}", mylib::to_json(&r));
        } else {
            println!("可选功能:json 未启用,to_json 不存在(调用它会编译报错)");
        }
    }
}

输出:

1
2
3
4
5
6
7
8
9
--- 默认构建(default 含 json)---
核心功能:小明:92 分
可选功能:{"name":"小明","score":92}
--- --no-default-features ---
核心功能:小明:92 分
可选功能:json 未启用,to_json 不存在(调用它会编译报错)
--- --no-default-features --features json ---
核心功能:小明:92 分
可选功能:{"name":"小明","score":92}

模拟靠运行时布尔分叉;真实项目里 feature 关着时 to_json 在编译期就被移除,调用它直接报错——用错组合在编译期暴露,正是好事。本地按核心概念配置跑三种构建对比即可。

示例 4:feature 统一模拟

两个包对同一依赖请求不同 feature,Cargo 取并集;resolver 2 让开发依赖的额外 feature 只在测试时生效。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use std::collections::BTreeSet;

fn union<'a>(a: &[&'a str], b: &[&'a str]) -> BTreeSet<&'a str> {
    a.iter().chain(b.iter()).copied().collect()
}

fn main() {
    let app_wants = ["rt"];
    let web_wants = ["full", "rt", "net", "time"];
    let unified = union(&app_wants, &web_wants);
    println!("app 请求:{:?}", app_wants);
    println!("web 请求:{:?}", web_wants);
    println!("统一后 tokio 实际启用的 feature:{:?}", unified);
    println!("结论:app 没要求 net/time,但同一份 tokio 被编成 full,app 也能用到");
    println!();
    let normal = union(&["rt"], &[]);
    let test = union(&["rt"], &["test-util"]);
    println!("cargo build 时:{:?}", normal);
    println!("cargo test  时:{:?}(test-util 只在测试构建出现)", test);
    println!("排查命令:cargo tree -e features -i tokio");
}

输出:

1
2
3
4
5
6
7
app 请求:["rt"]
web 请求:["full", "rt", "net", "time"]
统一后 tokio 实际启用的 feature:{"full", "net", "rt", "time"}
结论:app 没要求 net/time,但同一份 tokio 被编成 full,app 也能用到
cargo build 时:{"rt"}
cargo test  时:{"rt", "test-util"}
排查命令:cargo tree -e features -i tokio

本地复现:工作空间两成员对同一包开不同 feature,跑 cargo tree -e features -i <包名> 看统一结果;只构建单个成员再对比。

常见坑

  • 以为 "1.0" 是精确版本。它是 >=1.0.0, <2.0.0;靠锁文件固定实际版本,升级用 cargo update。
  • 库把需求写太窄。serde = "=1.0.200" 会让下游难以统一版本;库的需求应给足兼容范围。
  • 用 cfg! 守可选依赖。两个分支都编译,关着 feature 时照样报错。守依赖用 #[cfg(...)]。
  • feature 拼错静默失效。看到 unexpected cfg condition 警告先核对 [features] 里的名字。
  • 设计互斥 feature。下游统一打开两个互斥 feature 就炸。必须叠加友好,互斥选择用运行时配置。
  • default 关不掉。CI 加 cargo test --no-default-features 与 --all-features 两个极端验证。
  • 可选依赖没用 dep:。json = ["serde"] 把 serde 暴露成公开 feature。用 dep:serde 后只能通过你定义的 feature 启用。
  • 惊讶于别人打开了你的 feature。这是统一机制的正常行为,用 cargo tree -e features -i <包名> 查请求方。
  • cargo build 与 cargo test 行为不同。resolver 2 下 dev-dependencies 的 feature 只在测试构建生效,别把只在测试里成立的假设写进业务代码。
  • 重复版本膨胀。cargo tree -d 查多版本共存;两个主版本意味着两套类型,跨版本传类型会报不匹配。

动手练习

本地做一个带 features 的库,走一遍三种构建:

  1. cargo new feat-demo --lib,加可选依赖 serde = { version = "1.0", features = ["derive"], optional = true }、serde_json = { version = "1.0", optional = true },写 [features] default = ["json"]、json = ["dep:serde", "dep:serde_json"]。
  2. src/lib.rs 写 Record 与 summary;用 #[cfg(feature = "json")] 守住 to_json(给 Record 加 #[cfg_attr(feature = "json", derive(serde::Serialize))],内部用 serde_json::to_string)。src/main.rs 打印 summary,并用 cfg!(feature = "json") 分叉打印 JSON 或“json 未启用”。
  3. 依次运行三种构建(默认、--no-default-features、再加 --features json);跑 cargo tree -e features -i serde;最后无条件调用 to_json 并以 --no-default-features 构建,读报错。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// src/lib.rs(补全 to_json)
pub struct Record {
    pub name: String,
    pub score: u32,
}

pub fn summary(r: &Record) -> String {
    format!("{}:{} 分", r.name, r.score)
}

#[cfg(feature = "json")]
pub fn to_json(r: &Record) -> String {
    // 提示:Record 需实现 serde::Serialize,用 serde_json::to_string(r).unwrap()
    todo!()
}

期望输出(默认构建):

1
2
核心功能:小明:92 分
可选功能:{"name":"小明","score":92}

思考题:

  1. 把 json = ["dep:serde", "dep:serde_json"] 改成 json = ["serde", "serde_json"],下游能多做什么?为什么 dep: 更好?
  2. 你的库被 A 依赖(A 打开 json)、同时被 B 依赖(B 没打开)。最终库带不带 json?B 能调用 to_json 吗?说明 feature 设计要守什么原则?
  3. cargo test 通过、cargo build 报函数不存在。结合 resolver 2 的 dev-dependencies 规则,说说可能原因与排查命令。

小结与预告

核心就四句话:依赖声明写的是版本需求,默认插入符语义允许兼容升级,Cargo.lock 记录实际选定的精确版本;features 是编译期叠加开关,可选依赖用 optional = true 加 dep: 启用,default 可被关掉且关掉后必须仍能编译;#[cfg(...)] 整段移除代码、能守可选依赖,cfg! 只产生布尔值、两分支都要编译;同一依赖的 feature 取并集,resolver 2 只在平台、开发依赖、构建依赖三处分开解析,排查用 cargo tree -e features -i <包名>。

下一节 14.4:profile 与发布配置。依赖与功能开关就位后,讲优化等级、调试信息与发布产物怎么控制。


配套练习:在学习站动手练这一节

本文代码基于 Rust 1.8x / Edition 2024 验证。

JerryHome · 记录技术与生活