rust使用速查

1139 字
6 分钟
rust使用速查

哈哈,恭喜!🎉 Rust 确实比 C++ 友好多了,特别是包管理和工具链方面。让我给你一些 Rust 的实用技巧,让你更爽:

1. Rust 常用命令速查#

Terminal window
# 1. 项目管理
cargo new my_project # 创建新项目
cargo init # 在当前目录初始化
cargo build # 编译
cargo run # 编译并运行
cargo check # 快速检查(不生成二进制)
cargo test # 运行测试
cargo bench # 运行基准测试
# 2. 依赖管理
cargo add package_name # 添加依赖(需要 cargo-edit)
cargo update # 更新依赖
cargo tree # 查看依赖树
cargo audit # 安全检查
# 3. 代码质量
cargo fmt # 格式化代码
cargo clippy # 代码检查(类似 ESLint)
cargo doc --open # 生成并打开文档

2. 安装实用工具#

Terminal window
# 安装 cargo-edit(方便添加依赖)
cargo install cargo-edit
# 安装 cargo-watch(文件变化时自动重新编译)
cargo install cargo-watch
# 安装 cargo-make(类似 Makefile)
cargo install cargo-make
# 安装 cargo-generate(从模板生成项目)
cargo install cargo-generate
# 安装 cargo-udeps(查找未使用的依赖)
cargo install cargo-udeps

3. VS Code 配置#

安装这些扩展:

  • rust-lang.rust-analyzer(必装)
  • bungcip.better-toml(TOML 语法高亮)
  • serayuzgur.crates(依赖管理)
  • vadimcn.vscode-lldb(调试器)

.vscode/settings.json

{
"rust-analyzer.check.command": "clippy",
"rust-analyzer.checkOnSave": true,
"rust-analyzer.cargo.allFeatures": true,
"editor.formatOnSave": true,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer"
}
}

4. 常用依赖推荐#

# Cargo.toml 常用依赖
[dependencies]
# 命令行工具
clap = { version = "4.0", features = ["derive"] } # 命令行解析
indicatif = "0.17.0" # 进度条
colored = "2.0.0" # 彩色输出
anyhow = "1.0.0" # 错误处理
thiserror = "1.0.0" # 自定义错误
# 数据处理
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_yaml = "0.9"
csv = "1.2"
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1.0", features = ["full"] }
# 实用工具
chrono = "0.4.0" # 日期时间
regex = "1.0" # 正则表达式
rand = "0.8.0" # 随机数
rayon = "1.0" # 并行计算

5. 快速开发模板#

Terminal window
# 使用模板创建项目
cargo generate --git https://github.com/rust-cli/cli-template.git --name my-cli
# 或者创建自己的模板
cargo new --lib my-lib-template

6. 性能优化技巧#

// 1. 使用 release 模式编译
cargo build --release
// 2. 使用 #[inline] 标记小函数
#[inline]
fn add(a: i32, b: i32) -> i32 {
a + b
}
// 3. 避免不必要的克隆
fn process_string(s: &str) { /* ... */ } // 借用而不是拥有
// 4. 使用迭代器而不是循环
let sum: i32 = vec![1, 2, 3].iter().sum();
// 5. 使用 Cow(写时复制)
use std::borrow::Cow;
fn process(input: &str) -> Cow<str> {
if input.contains("bad") {
Cow::Owned(input.replace("bad", "good"))
} else {
Cow::Borrowed(input)
}
}

7. 调试技巧#

// 1. 使用 dbg! 宏
let x = 5;
let y = dbg!(x * 2) + 1; // 打印中间值
// 2. 使用 println! 格式化
println!("x = {x}, y = {y}"); // Rust 1.58+ 支持
// 3. 使用 tracing 库进行结构化日志
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
tracing::info!("Starting application");
tracing::debug!("Debug info: {:?}", some_data);
tracing::error!("Something went wrong");
}

8. 实用脚本#

创建 dev.ps1

Terminal window
# Rust 开发助手
param(
[string]$Command = "help"
)
switch ($Command) {
"run" {
cargo run
}
"watch" {
cargo watch -x run
}
"test" {
cargo test -- --nocapture
}
"bench" {
cargo bench
}
"clean" {
cargo clean
Remove-Item -Recurse -Force target -ErrorAction SilentlyContinue
}
"deps" {
cargo tree
}
"audit" {
cargo audit
}
"update" {
cargo update
rustup update
}
default {
Write-Host "可用命令:" -ForegroundColor Cyan
Write-Host " .\dev.ps1 run - 运行项目" -ForegroundColor Green
Write-Host " .\dev.ps1 watch - 监视并自动运行" -ForegroundColor Green
Write-Host " .\dev.ps1 test - 运行测试" -ForegroundColor Green
Write-Host " .\dev.ps1 bench - 运行基准测试" -ForegroundColor Green
Write-Host " .\dev.ps1 clean - 清理构建" -ForegroundColor Green
Write-Host " .\dev.ps1 deps - 查看依赖树" -ForegroundColor Green
Write-Host " .\dev.ps1 audit - 安全检查" -ForegroundColor Green
Write-Host " .\dev.ps1 update - 更新所有" -ForegroundColor Green
}
}

9. 学习资源#

## 在线学习
- [Rust 官方教程](https://doc.rust-lang.org/book/)
- [Rust by Example](https://doc.rust-lang.org/rust-by-example/)
- [Rustlings](https://github.com/rust-lang/rustlings) - 小练习
- [Exercism Rust Track](https://exercism.org/tracks/rust)
## 实用工具
- [crates.io](https://crates.io/) - Rust 包仓库
- [docs.rs](https://docs.rs/) - 文档自动生成
- [play.rust-lang.org](https://play.rust-lang.org/) - 在线运行
## 社区
- [Rust 中文社区](https://rustcc.cn/)
- [r/rust](https://www.reddit.com/r/rust/)
- [Rust Discord](https://discord.gg/rust-lang)

10. 快速开始项目#

Terminal window
# 创建 CLI 工具
cargo new my-cli --bin
cd my-cli
# 添加依赖
cargo add clap --features derive
cargo add anyhow
cargo add colored
# 运行
cargo run -- --name World --count 3

Rust 的编译器和工具链确实比 C++ 友好太多了!享受编码吧!🚀

创建批处理文件用于管理rust的linker

Terminal window
@echo off
echo 选择MinGW版本:
echo 1. Scoop版本 (C:\Users\user\scoop\apps\mingw-winlibs\current\bin)
echo 2. CLion版本 (D:\JetBrains\CLion 2025.1.4\bin\mingw\bin)
echo 3. OpenCV版本 (E:\opencv\mingw-build\install\x64\mingw\bin)
set /p choice="请输入选择 (1-3): "
if "%choice%"=="1" (
set PATH=C:\Users\user\scoop\apps\mingw-winlibs\current\bin;%PATH%
echo 已切换到Scoop MinGW
) else if "%choice%"=="2" (
set PATH=D:\JetBrains\CLion 2025.1.4\bin\mingw\bin;%PATH%
echo 已切换到CLion MinGW
) else if "%choice%"=="3" (
set PATH=E:\opencv\mingw-build\install\x64\mingw\bin;%PATH%
echo 已切换到OpenCV MinGW
) else (
echo 无效选择
)

使用Scoop的MinGW-gcc的powershell:

Terminal window
# 创建 Rust 配置文件
$rustConfig = @"
# 使用 Scoop 的 MinGW
[target.x86_64-pc-windows-gnu]
linker = "C:\\Users\\user\\scoop\\apps\\mingw-winlibs\\current\\bin\\gcc.exe"
ar = "C:\\Users\\user\\scoop\\apps\\mingw-winlibs\\current\\bin\\ar.exe"
# 设置默认目标
[build]
target = "x86_64-pc-windows-gnu"
"@
$rustConfig | Out-File -Encoding UTF8 "$env:USERPROFILE\.cargo\config.toml"
Write-Host "✅ Rust 配置已更新" -ForegroundColor Green

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
rust使用速查
https://jiheweihuan.github.io/posts/rust-quick-ref/
作者
几何为欢
发布于
2026-03-10
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
几何为欢
CUMT 2025级大一在读 人工智障专业 CTF/ACM入门ing 希望成为CS/AI人才喵!
公告
欢迎来到我的博客!这是一则示例公告。
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
13
分类
7
标签
19
总字数
6,280
运行时长
0
最后活动
0 天前

目录