Cargo 怎么换国内源?
更新时间:2026-09-20。问题驱动短答页。国内直连 crates.io 经常超时,配置镜像后
cargo build拉依赖能快一个数量级。Cargo 清单与依赖机制见 Cargo.toml 详解。
一句话回答
编辑 ~/.cargo/config.toml(Windows 是 %USERPROFILE%\.cargo\config.toml,没有就新建),用 [source.crates-io] 的 replace-with 指向国内镜像;推荐字节的 rsproxy 并使用 sparse 索引。
全局配置(推荐 rsproxy)
# ~/.cargo/config.toml
[source.crates-io]
replace-with = 'rsproxy-sparse'
[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"
[registries.rsproxy]
index = "sparse+https://rsproxy.cn/index/"
[net]
git-fetch-with-cli = true配好后任意项目 cargo build/cargo add 都走镜像。
其他常用镜像
# 清华 TUNA(sparse)
[source.crates-io]
replace-with = 'tuna'
[source.tuna]
registry = "sparse+https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/"
# 中科大 USTC
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"旧教程常见
git+https://.../index写法。新写法用sparse+前缀:稀疏索引只按需拉取相关条目,比克隆整棵 git 索引省大量时间(Cargo 1.68+ 默认官方源也已是 sparse)。
只对单个项目生效
把同样的 config.toml 放到项目根的 .cargo/config.toml(团队可提交、让所有协作者统一走内网镜像);全局配置对所有项目生效。两者都在时项目级覆盖全局。
配置后
cargo fetch # 预拉取/刷新依赖索引
cargo build # 正常构建,已走镜像常见坑
- 配完仍慢:用了
git+全量索引,换成sparse+;或之前缓存损坏,删~/.cargo/registry后重试。 - 镜像同步延迟导致新版本拉不到:个别镜像比官方慢,临时
replace-with回官方或换 rsproxy。 - 公司内网还要过代理:设
HTTPS_PROXY环境变量,或在内网搭 crates 代理(如 kitsugi/panamax)。 - 把带镜像的 config.toml 提交到开源项目:可能影响外部贡献者,项目级配置需团队确认,个人偏好放全局。
- 路径放错:是
.cargo/config.toml(旧版也认config无扩展名),不是写进Cargo.toml。
Cargo 工程与 release 构建见 Cargo 与编译模型。
总结
Cargo 换国内源只需在 ~/.cargo/config.toml(全局)或项目 .cargo/config.toml(局部)里用 [source.crates-io] replace-with 指向 rsproxy/清华/中科大镜像,并优先用 sparse+ 前缀的稀疏索引以避免克隆整棵 git 索引;配完 cargo fetch/build 即生效,注意镜像可能有同步延迟、公司网络要再设 HTTPS_PROXY 或内网代理,且个人镜像偏好应放全局而非提交进开源项目。