rust使用速查
1139 字
6 分钟
rust使用速查
哈哈,恭喜!🎉 Rust 确实比 C++ 友好多了,特别是包管理和工具链方面。让我给你一些 Rust 的实用技巧,让你更爽:
1. Rust 常用命令速查
# 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. 安装实用工具
# 安装 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-udeps3. 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. 快速开发模板
# 使用模板创建项目cargo generate --git https://github.com/rust-cli/cli-template.git --name my-cli
# 或者创建自己的模板cargo new --lib my-lib-template6. 性能优化技巧
// 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:
# 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. 快速开始项目
# 创建 CLI 工具cargo new my-cli --bincd my-cli
# 添加依赖cargo add clap --features derivecargo add anyhowcargo add colored
# 运行cargo run -- --name World --count 3Rust 的编译器和工具链确实比 C++ 友好太多了!享受编码吧!🚀
创建批处理文件用于管理rust的linker
@echo offecho 选择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:
# 创建 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支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!