bigywater.tech
Rust · 152

Cargo.lock 的作用

Cargo.lock 到底锁了什么?什么时候该提交?--locked 有什么用?篡改它会怎样?这篇用一个最小项目把锁文件的内容、校验、可复现性和提交约定逐个验证。

version = 4
本机 cargo 生成的锁文件格式版本
SHA-256
锁文件为每个 registry 包记录的校验和
--locked
让 CI 在锁文件过期时失败的开关

锁文件的内容

实测 · 本机执行输出
  Cargo.lock(完整内容):
    # This file is automatically @generated by Cargo.
    # It is not intended for manual editing.
    version = 4
    
    [[package]]
    name = "itoa"
    version = "1.0.18"
    source = "registry+https://github.com/rust-lang/crates.io-index"
    checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
    
    [[package]]
    name = "u152"
    version = "0.1.0"
    dependencies = [
     "itoa",
    ]

依赖版本的解析规则见Cargo.toml 依赖解析。

--locked

实测 · 本机执行输出
  Cargo.toml 加了依赖但锁文件没更新,cargo build --locked:
    Updating crates.io index
    error: cannot update the lock file <实验目录>/proj/u152/Cargo.lock because --locked was passed to prevent this
    help: to generate the lock file without accessing the network, remove the --locked flag and use --offline instead.
  不加 --locked 时 cargo 自动更新锁文件:退出码 0;锁文件里的包数:3

checksum

实测 · 本机执行输出
  把 itoa 的 checksum 前 8 位改成 deadbeef 后构建:
    error: checksum for `itoa v1.0.18` changed between lock files
    this could be indicative of a few possible errors:
    * the lock file is corrupt
    * a replacement source in use (e.g., a mirror) returned a different checksum
    * the source itself may be corrupt in one way or another
    unable to verify that `itoa v1.0.18` is the same as when the lockfile was generated

可复现构建

实测 · 本机执行输出
  cargo build --locked 退出码 0
  cargo tree --locked:
    u152 v0.1.0 (<实验目录>/proj/u152)
    ├── itoa v1.0.5
    └── semver v1.0.28

在工作区里统一依赖见Workspace 依赖管理。

要不要提交

实测 · 本机执行输出
  cargo new --bin:.gitignore 内容 ['/target'](是否忽略 Cargo.lock: False)
  cargo new --lib:.gitignore 内容 ['/target'](是否忽略 Cargo.lock: False)

分步演示

Cargo.lock
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / rustc 1.98.1(brew)/ cargo 1.98.1;单个文件用 rustc 直接编译,需要依赖时用 cargo(经代理从 crates.io 下载);计时用 std::time::Instant,数字每次运行会有小幅抖动。crates.io 为 2026-10 的最新数据
    • 没有验证:git 依赖在锁文件里的 source 格式、vendor 目录与离线构建、cargo package 是否把 Cargo.lock 打进发布包、锁文件合并冲突的处理、cargo-deny 对锁文件的审计(见依赖安全审计一篇)
    京ICP备2026067502号-1京公网安备11010502063487号