Rust Overview & Environment Setup
Why Rust for backends, zero-cost safety guarantees, rustup toolchain, cargo, and your first HTTP endpoint.
Why Rust on the Backend
Rust delivers C++ speed with a compile-time guarantee: no null pointer dereferences, no use-after-free, no data races — enforced by the borrow checker, not a runtime GC. That means predictable latency, tiny memory footprints and rewritable hot paths, which is why Cloudflare, Discord and AWS build core services with it.
- Best for: API gateways, proxies, databases, daemons, WebAssembly, CLI tools.
- Watch out: longer compile times and a steeper learning curve at the start.
rustup, cargo, crates.io
# 安装工具链(rustup 管理多套版本)
# Windows: 官网 rustup-init.exe;macOS/Linux:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 国内镜像(~/.cargo/config.toml)
# [source.crates-io]
# replace-with = 'ustc'
# [source.ustc]
# registry = 'sparse+https://mirrors.ustc.edu.cn/crates.io-index/'
rustc --version
cargo --version
cargo new shop --bin # 新建二进制项目
cargo build # 调试构建(target/debug)
cargo build --release # 发布构建(-O 级优化)
cargo run # 编译并运行
cargo test # 跑测试
cargo fmt && cargo clippy # 格式化 + 静态检查
Cargo is compiler, package manager and test runner in one: Cargo.toml declares dependencies, cargo update bumps them, and docs.rs documents every published crate.
The Borrow Checker in One Minute
fn main() {
let mut v = vec![1, 2, 3]; // v 拥有堆数据
let r = &v; // 不可变借用(多个 OK)
// v.push(4); // ✗ 同时存在不可变借用,不能修改
println!("{:?}", r);
let r2 = &mut v; // 可变借用(必须独占)
r2.push(4);
// println!("{:?}", r); // ✗ r 在此已失效
println!("{:?}", v); // ✓ 借用结束后可再读
}
// 三条规则:
// 1. 每个值有且仅有一个所有者
// 2. 借用可多个(只读)或一个(可写),二者互斥
// 3. 值离开作用域时自动 drop(无 GC)
Your First HTTP Endpoint
# Cargo.toml
# [dependencies]
# axum = "0.7"
# tokio = { version = "1", features = ["full"] }
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(|| async { "ok" }))
.route("/", get(|| async { "Hello, BackendWiki" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}后端为什么用 Rust
Rust 既有 C++ 的速度,又在编译期保证:没有空指针解引用、没有释放后使用、没有数据竞争——靠借用检查器而非运行时 GC 兜底。这意味着可预期的延迟、很小的内存占用,因此 Cloudflare、Discord、AWS 都用它写核心服务。
- 最适合:API 网关、代理、数据库、常驻服务、WebAssembly、CLI。
- 注意:编译时间较长,入门曲线偏陡。
rustup、cargo 与 crates.io
# 安装工具链(rustup 管理多套版本)
# Windows: 官网 rustup-init.exe;macOS/Linux:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 国内镜像(~/.cargo/config.toml)
# [source.crates-io]
# replace-with = 'ustc'
# [source.ustc]
# registry = 'sparse+https://mirrors.ustc.edu.cn/crates.io-index/'
rustc --version
cargo --version
cargo new shop --bin # 新建二进制项目
cargo build # 调试构建(target/debug)
cargo build --release # 发布构建(-O 级优化)
cargo run # 编译并运行
cargo test # 跑测试
cargo fmt && cargo clippy # 格式化 + 静态检查
Cargo 集编译器、包管理器与测试运行器于一身:Cargo.toml 声明依赖,cargo update 升级版本,docs.rs 有每个 crate 的文档。
一分钟看懂借用检查器
fn main() {
let mut v = vec![1, 2, 3]; // v 拥有堆数据
let r = &v; // 不可变借用(多个 OK)
// v.push(4); // ✗ 同时存在不可变借用,不能修改
println!("{:?}", r);
let r2 = &mut v; // 可变借用(必须独占)
r2.push(4);
// println!("{:?}", r); // ✗ r 在此已失效
println!("{:?}", v); // ✓ 借用结束后可再读
}
// 三条规则:
// 1. 每个值有且仅有一个所有者
// 2. 借用可多个(只读)或一个(可写),二者互斥
// 3. 值离开作用域时自动 drop(无 GC)
第一个 HTTP 接口
# Cargo.toml
# [dependencies]
# axum = "0.7"
# tokio = { version = "1", features = ["full"] }
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(|| async { "ok" }))
.route("/", get(|| async { "Hello, BackendWiki" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}