Rust 环境搭建
概述
本章将指导你在不同操作系统上安装和配置 Rust 开发环境,包括 Rust 编译器、Cargo 包管理器、开发工具和编辑器配置。
🛠️ 安装 Rust
官方安装方式(推荐)
Windows 系统
bash
# 方法 1:使用 rustup(推荐)
# 访问 https://rustup.rs/ 下载 rustup-init.exe
# 或者使用 PowerShell
Invoke-WebRequest -Uri "https://win.rustup.rs/" -OutFile "rustup-init.exe"
.\rustup-init.exe
# 方法 2:使用 Chocolatey
choco install rust
# 方法 3:使用 Scoop
scoop install rustmacOS 系统
bash
# 方法 1:使用 rustup(推荐)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 方法 2:使用 Homebrew
brew install rust
# 重新加载环境变量
source ~/.bashrc
# 或者
source ~/.zshrcLinux 系统
bash
# Ubuntu/Debian
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Arch Linux
sudo pacman -S rust
# CentOS/RHEL/Fedora
# 先安装 rustup,然后安装 Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 添加到 PATH
echo 'source ~/.cargo/env' >> ~/.bashrc
source ~/.bashrc验证安装
bash
# 检查 Rust 版本
rustc --version
# 输出示例:rustc 1.75.0 (82e1608df 2023-12-21)
# 检查 Cargo 版本
cargo --version
# 输出示例:cargo 1.75.0 (1d8b05cdd 2023-11-20)
# 查看工具链信息
rustup show🔧 Rustup 工具链管理
基本概念
rust
// Rust 工具链包含以下组件:
// - rustc: Rust 编译器
// - cargo: 包管理器和构建工具
// - rustfmt: 代码格式化工具
// - clippy: 代码检查工具
// - rust-docs: 本地文档管理工具链
bash
# 查看已安装的工具链
rustup toolchain list
# 安装特定版本
rustup toolchain install stable
rustup toolchain install beta
rustup toolchain install nightly
# 设置默认工具链
rustup default stable
# 更新工具链
rustup update
# 安装组件
rustup component add clippy
rustup component add rustfmt
rustup component add rust-src
# 查看已安装组件
rustup component list --installed目标平台管理
bash
# 查看支持的目标平台
rustup target list
# 添加交叉编译目标
rustup target add x86_64-pc-windows-gnu
rustup target add aarch64-apple-darwin
rustup target add wasm32-unknown-unknown
# 为特定目标编译
cargo build --target x86_64-pc-windows-gnu📝 开发工具配置
Visual Studio Code(推荐)
json
// .vscode/settings.json
{
"rust-analyzer.check.command": "clippy",
"rust-analyzer.cargo.features": "all",
"rust-analyzer.procMacro.enable": true,
"rust-analyzer.imports.granularity.group": "module",
"rust-analyzer.completion.addCallArgumentSnippets": true,
"rust-analyzer.completion.addCallParenthesis": true,
"editor.formatOnSave": true,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.tabSize": 4,
"editor.insertSpaces": true
}
}必备扩展
bash
# VS Code 扩展列表
code --install-extension rust-lang.rust-analyzer
code --install-extension vadimcn.vscode-lldb
code --install-extension serayuzgur.crates
code --install-extension dustypomerleau.rust-syntaxIntelliJ IDEA / CLion
rust
// 安装 Rust 插件
// File -> Settings -> Plugins -> 搜索 "Rust"
// 安装 "Rust" 插件
// 配置 Rust 工具链
// File -> Settings -> Languages & Frameworks -> Rust
// Toolchain location: ~/.cargo/bin
// Standard library: ~/.rustup/toolchains/stable-x86_64-unknown-linux-gnuVim/Neovim 配置
vim
" ~/.vimrc 或 ~/.config/nvim/init.vim
" 安装 vim-plug 插件管理器
call plug#begin('~/.vim/plugged')
Plug 'rust-lang/rust.vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'dense-analysis/ale'
call plug#end()
" Rust 配置
let g:rustfmt_autosave = 1
let g:rust_clip_command = 'xclip -selection clipboard'
" CoC 配置
let g:coc_global_extensions = ['coc-rust-analyzer']🚀 创建第一个项目
使用 Cargo 创建项目
bash
# 创建新的二进制项目
cargo new hello_rust
cd hello_rust
# 创建新的库项目
cargo new my_library --lib
# 查看项目结构
tree hello_rust项目结构解析
rust
// hello_rust/
// ├── Cargo.toml # 项目配置文件
// ├── src/ # 源代码目录
// │ └── main.rs # 主程序文件
// └── target/ # 编译输出目录(生成后)
// Cargo.toml 示例
[package]
name = "hello_rust"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0"
tokio = { version = "1.0", features = ["full"] }
[dev-dependencies]
assert_cmd = "2.0"第一个 Rust 程序
rust
// src/main.rs
fn main() {
println!("Hello, Rust!");
// 变量和类型推断
let name = "世界";
let number = 42;
println!("你好,{}! 幸运数字是 {}", name, number);
// 可变变量
let mut count = 0;
count += 1;
println!("计数器: {}", count);
// 函数调用
let result = add_numbers(10, 20);
println!("10 + 20 = {}", result);
}
fn add_numbers(a: i32, b: i32) -> i32 {
a + b // 没有分号,表示返回值
}运行和构建
bash
# 运行项目
cargo run
# 检查代码(不生成可执行文件)
cargo check
# 构建项目
cargo build
# 发布构建(优化版本)
cargo build --release
# 运行测试
cargo test
# 生成文档
cargo doc --open🔍 开发工具介绍
Clippy - 代码检查工具
bash
# 安装 Clippy
rustup component add clippy
# 运行代码检查
cargo clippy
# 严格模式检查
cargo clippy -- -D warningsrust
// Clippy 示例
fn inefficient_function() {
let mut vec = Vec::new();
for i in 0..10 {
vec.push(i); // Clippy 建议:使用 (0..10).collect()
}
let s = "hello".to_string();
if s == "hello" { // Clippy 建议:直接比较 &str
println!("match!");
}
}
// 改进后的代码
fn efficient_function() {
let vec: Vec<i32> = (0..10).collect();
let s = "hello";
if s == "hello" {
println!("match!");
}
}Rustfmt - 代码格式化
bash
# 安装 rustfmt
rustup component add rustfmt
# 格式化代码
cargo fmt
# 检查格式(不修改文件)
cargo fmt -- --checktoml
# rustfmt.toml 配置文件
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Unix"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = trueRust Analyzer - 语言服务器
rust
// rust-analyzer 提供的功能:
// 1. 智能补全
// 2. 错误检查
// 3. 类型提示
// 4. 重构工具
// 5. 代码导航
fn example_function() {
let numbers = vec![1, 2, 3, 4, 5];
// rust-analyzer 会提供:
// - numbers 的类型提示:Vec<i32>
// - .iter() 方法的自动补全
// - 错误诊断和修复建议
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum);
}🌐 配置代理和镜像
Cargo 镜像配置
toml
# ~/.cargo/config.toml
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
# 使用字节跳动镜像
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中国大陆用户优化
bash
# 设置环境变量
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"
# 或者在 ~/.bashrc 中添加
echo 'export RUSTUP_DIST_SERVER="https://rsproxy.cn"' >> ~/.bashrc
echo 'export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"' >> ~/.bashrc🧪 环境验证
完整的测试项目
rust
// src/main.rs
use std::collections::HashMap;
fn main() {
println!("🦀 Rust 环境测试");
// 测试基本语法
test_basic_syntax();
// 测试标准库
test_standard_library();
// 测试外部依赖(需要在 Cargo.toml 中添加)
test_external_crate();
}
fn test_basic_syntax() {
println!("\n✅ 基本语法测试");
let message = "Hello, Rust!";
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.iter().sum();
println!("消息: {}", message);
println!("数组和: {}", sum);
}
fn test_standard_library() {
println!("\n✅ 标准库测试");
let mut map = HashMap::new();
map.insert("language", "Rust");
map.insert("type", "Systems Programming");
for (key, value) in &map {
println!("{}: {}", key, value);
}
}
fn test_external_crate() {
println!("\n✅ 外部依赖测试");
// 如果添加了 serde 依赖,可以测试序列化
println!("外部 crate 工作正常");
}
#[cfg(test)]
mod tests {
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}
#[test]
fn test_string_operations() {
let s = String::from("hello");
assert_eq!(s.len(), 5);
}
}性能基准测试
toml
# Cargo.toml
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "my_benchmark"
harness = falserust
// benches/my_benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
n => fibonacci(n-1) + fibonacci(n-2),
}
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);📝 本章小结
通过本章学习,你应该掌握了:
环境搭建
- ✅ 在不同平台安装 Rust
- ✅ 配置 rustup 工具链管理
- ✅ 设置开发工具和编辑器
- ✅ 配置 Cargo 镜像和代理
开发工具
- ✅ Cargo 项目管理
- ✅ Clippy 代码检查
- ✅ Rustfmt 代码格式化
- ✅ Rust Analyzer 语言服务
最佳实践
- 使用 rustup 管理工具链
- 配置编辑器插件提高效率
- 定期更新 Rust 版本
- 使用 Clippy 保证代码质量
继续学习:下一章 - Cargo 教程