Skip to content

Rust cargo 换源加速:crates.io 国内镜像配置

cargo build 卡在 Updating crates.io index、下载依赖龟速——因为默认走海外的 crates.io。给 cargo 配国内镜像即可。现代 cargo 推荐用 sparse 协议,增量拉取索引更快。

一、配置镜像(推荐 rsproxy + sparse)

编辑(没有就新建)~/.cargo/config.toml:

toml
[source.crates-io]
replace-with = 'rsproxy-sparse'

[source.rsproxy]
registry = "https://rsproxy.cn/crates.io-index"

[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"

[registries.rsproxy]
index = "https://rsproxy.cn/crates.io-index"

[net]
git-fetch-with-cli = true

sparse+ 前缀启用稀疏索引协议,不用再 clone 整个庞大的 index git 仓库,首次拉取快很多。cargo 1.70+ 默认支持 sparse。

二、换中科大镜像(备选)

toml
[source.crates-io]
replace-with = 'ustc'

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"

三、加速 crate 编译产物 / 二进制

安装二进制工具(如 cargo install)时若还慢,通常是从 GitHub 拉源码或 Release:

  • 给 git 配代理:见 Git 设置代理;
  • config.toml 里已加的 git-fetch-with-cli = true 会让 cargo 用系统 git,从而复用你的 git 代理配置。

四、rustup 本身换源(装 Rust 工具链慢)

如果连 rustup 安装 / 更新工具链都慢,设置 rustup 镜像环境变量:

bash
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"

写进 ~/.zshrc / ~/.bashrc 后再运行 rustup 相关命令。

五、验证

bash
# 随便 build 一个有依赖的项目,观察 index 更新和下载速度
cargo build

# 或强制更新索引
cargo update

首次拉 sparse 索引后,后续会缓存,速度更快。

常见问题

Q:改了 config 还是走 crates.io?

  • 确认文件是 ~/.cargo/config.toml(新版)或 ~/.cargo/config(旧版无扩展名),别放错位置。
  • 项目根目录的 .cargo/config.toml 优先级更高,检查是否被项目内配置覆盖。

Q:报 sparse 相关错误? cargo 版本过低不支持 sparse,rustup update 升级,或改用非 sparse 的 registry = "https://..." 写法。

小结

  • 写好 ~/.cargo/config.toml,优先用 sparse 协议,索引更新最快。
  • git-fetch-with-cli = true 让 cargo 复用系统 git 代理,方便拉 GitHub 依赖。
  • 工具链慢就顺带设 RUSTUP_DIST_SERVER 镜像。

本文仅供技术学习与研究,请遵守所在国家/地区法律法规。

本站为技术学习交流站点,与 GitHub, Inc. 无任何隶属或官方关系。所有内容仅供技术研究与学习,请遵守所在国家/地区的法律法规。