Rust cargo 命令行工具使用教程

简介

cargoRust 的构建系统和包管理器,负责创建项目、编译代码、管理依赖、运行测试等,是日常开发中最常用的工具。

创建项目

shell 复制代码
cargo new project_name      # 创建 binary 项目(可执行)
cargo new --lib mylib       # 创建 library 项目(供其它项目调用)

它会创建一个项目结构:

shell 复制代码
project_name/
├── Cargo.toml        # 项目信息和依赖配置
└── src/
    └── main.rs       # 项目主入口(lib.rs 对于库)

项目结构和配置文件

Cargo.toml 是项目的核心配置文件,类似于 Javapom.xmlNode.jspackage.json

toml 复制代码
[package]
name = "my_project"
version = "0.1.0"
edition = "2025"

[dependencies]
rand = "0.8"     # 添加依赖

常用命令

编译项目

shell 复制代码
cargo build          # 构建项目(debug 模式)
cargo build --release  # 构建 release 模式(优化)

运行项目

shell 复制代码
cargo run

带参数运行

shell 复制代码
cargo run -- arg1 arg2

检查语法和错误(不编译生成目标文件)

shell 复制代码
cargo check

添加依赖包

shell 复制代码
cargo add serde        # 需要安装 cargo-edit 插件

安装 cargo-edit

shell 复制代码
cargo install cargo-edit

依赖管理

在 Cargo.toml 中手动添加:

toml 复制代码
[dependencies]
serde = "1.0"
reqwest = { version = "0.11", features = ["json"] }

添加本地 crate:

toml 复制代码
[dependencies]
mycrate = { path = "../mycrate" }

添加 Git 仓库依赖:

toml 复制代码
[dependencies]
mycrate = { git = "https://github.com/user/mycrate.git" }

测试 & 文档

测试

shell 复制代码
cargo test

生成文档

shell 复制代码
cargo doc --open

发布 Crate 到 crates.io

shell 复制代码
cargo login                # 登录 crates.io(需要 token)
cargo publish              # 发布
cargo package              # 打包并检查

构建配置与工作区(workspace)

如果有多个 crate 项目组成一个工程:

根目录 Cargo.toml 配置:

toml 复制代码
[workspace]
members = [
    "core",
    "utils",
    "web"
]

常用 cargo 插件

shell 复制代码
cargo install cargo-edit         # 管理依赖(cargo add/remove/etc)
cargo install cargo-watch        # 自动监控并重编译
cargo install cargo-audit        # 审计安全问题
cargo install cargo-outdated     # 查看依赖是否过期

命令速查表

  • cargo new: 创建项目

  • cargo build:编译项目

  • cargo run:编译并运行

  • cargo check:检查代码是否可编译

  • cargo test:运行测试

  • cargo doc --open:生成并打开文档

  • cargo add xxx:添加依赖(需插件)

  • cargo update:更新依赖到最新版本

  • cargo clean:清理构建产物

  • cargo install:安装二进制 crate(如 ripgrep

相关推荐
swear011 小时前
VSCODE 插件 rust-analyzer 使用遇到的问题 快捷键查看定义
ide·vscode·rust
微小冷2 小时前
Rust图形界面教程:egui基础组件的使用
后端·rust·gui·egui·button·panel·用户图形界面
星释3 小时前
Rust 练习册 :Nucleotide Codons与生物信息学
开发语言·算法·rust
-大头.3 小时前
Rust高级类型与零成本抽象实战
stm32·单片机·rust
RustFS9 小时前
ansible + docker compose, RustFS MNMD 架构的一键部署之道
rust
Source.Liu10 小时前
【iso8601库】Time 类型解析模块详解(time.rs文件)
rust·iso8601
星释10 小时前
Rust 练习册 :Minesweeper与二维数组处理
开发语言·后端·rust
疏狂难除11 小时前
spiderdemo第22题与webassembly的跨域
开发语言·javascript·爬虫·rust·wasm·mitmproxy
国服第二切图仔15 小时前
Rust开发实战之操作SQLite数据库——从零构建数据持久化应用
数据库·rust·sqlite
2301_7965125221 小时前
Rust编程学习 - 为什么说Cow 代表的是Copy-On-Write, 即“写时复制技术”,它是一种高效的 资源管理手段
java·学习·rust