红锈于二二六:系统之语终得可亲
红锈已越鸿沟。二二四年间,人皆趋之若鹜,然鲜有用于生产。二二六之际,已运行于微软、谷歌、亚马逊、云锋及一代新创之企业。借检之术,昔似不可测,今则数十万开发者直觉洞明。其变何在?
采用之曲线
铁锈用户之调查,道其事:
- 二〇二三年:百分之二十八之应答者,用铁锈于生产
- 二〇二五年:百分之四十七之应答者,用铁锈于生产
- 至要者:学铁锈之满意率,自百分之四十二,升为百分之七十一
此言已非"学之艰",渐为"学之艰而值之"。
2026年何以使Rust更易亲近
一、错误信息更优
今之借用检查错误信息,已传为佳话。非但言"不可",更释其由,且示其解。
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
}
编译器之输出:
error[E0502]: cannot borrow `s` as immutable because it is also
borrowed as mutable
--> src/main.rs:4:13
|
3 | let r1 = &s;
| -- first borrow occurs here
4 | let r2 = &s;
| ^^ second borrow occurs here
5 | println!("{} and {}", r1, r2);
| -- first borrow needs to be valid
| for the duration of the borrow
help: consider using the reference count for shared ownership
help: consider using `Rc<String>` if you don't need exclusive ownership
较之C++之段错误,但言"段错误(核心转储)"而已。
2. 异步Rust稳定
异步/等待之语法稳定,生态亦显著成熟。
// Before (2024): Complex futures, Pin, Box, manual polling
// After (2026): Clean async/await like Go/Python
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let data = fetch_data("https://api.example.com/data").await?;
let processed = process(data).await;
save_to_db(processed).await?;
Ok(())
}
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
reqwest::get(url).await?.text().await
}
3. 仓库生态达临界量
今之 crates.io 生态,已备生产所需:
# Cargo.toml — Production Rust is just dependency management
[dependencies]
# Web framework
axum = "0.7"
tower = "0.4"
tower-http = { version = "0.5", features = ["cors", "compression"] }
# Async runtime
tokio = { version = "1", features = ["full"] }
# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Database
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
# Error handling
anyhow = "1"
thiserror = "2"
# Logging
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
# Testing
tokio-test = "0.4"
真实生产之例:Axum 中之 Web API
use axum::{
extract::{Path, State},
http::StatusCode,
response::Json,
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPoolOptions;
use std::sync::Arc;
use tower_http::cors::CorsLayer;
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
struct User {
id: i32,
name: String,
email: String,
}
#[derive(Clone)]
struct AppState {
db: sqlx::PgPool,
}
async fn create_user(
State(state): State<Arc<AppState>>,
Json(payload): Json<CreateUserPayload>,
) -> Result<(StatusCode, Json<User>), AppError> {
let user = sqlx::query_as::<_, User>(
r#"INSERT INTO users (name, email) VALUES ($1, $2)
RETURNING id, name, email"#
)
.bind(&payload.name)
.bind(&payload.email)
.fetch_one(&state.db)
.await?;
Ok((StatusCode::CREATED, Json(user)))
}
async fn get_user(
Path(user_id): Path<i32>,
State(state): State<Arc<AppState>>,
) -> Result<Json<User>, AppError> {
let user = sqlx::query_as::<_, User>(
"SELECT id, name, email FROM users WHERE id = $1"
)
.bind(user_id)
.fetch_optional(&state.db)
.await?
.ok_or(AppError::NotFound)?;
Ok(Json(user))
}
#[derive(Debug, thiserror::Error)]
enum AppError {
#[error("User not found")]
NotFound,
#[error("Database error: {0}")]
Database(#[from] sqlx::Error),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
AppError::Database(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
};
(status, Json(serde_json::json!({ "error": message }))).into_response()
}
}
type Response = axum::response::Response;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();
let db = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://user:pass@localhost/mydb")
.await?;
let state = Arc::new(AppState { db });
let app = Router::new()
.route("/users", post(create_user))
.route("/users/:id", get(get_user))
.layer(CorsLayer::permissive())
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await?;
axum::serve(listener, app).await?;
Ok(())
}
内存安全之辩:非复空谈
乙卯丙辰之际之巨变:改用 Rust 之组织,现实安全漏洞骤减.
// C/C++ memory vulnerabilities (common in production):
// - Buffer overflow
// - Use after free
// - Double free
// - Race conditions
// The National Security Agency (NSA) and CISA now recommend:
// "Consider migrating to memory-safe languages like Rust"
微软报曰:其 CVE(安全漏洞)之七十为内存安全之患。C/C++ 中,此患恒见。Rust 之借用检查器,则使之不可得而患.
Rust 与 Go:诚然较之
Rust與Go之爭,漸歸明確之共識:
| 用例 | 胜者 | 缘由 |
|---|---|---|
| 网络接口(简) | 往矣 | 书之速,足矣善其效 |
| 网络接口(高性能) | 铁锈 | 十倍之低延迟,可期之内存 |
| 系统编程 | 鈇 | 無需垃圾回收之記憶安全 |
| 網絡基礎設施 | 鈇 | Cloudflare、Fastly、AWS選鈇 |
| 微服務(吞吐量為關鍵) | 鈇 | Wizer、Shuttle、Encore選鈇 |
| 快速原型設計 | Go | 學習曲線更平緩 |
| 工具 | 或 | 皆优 |
| 嵌入式 | Rust | 无运行时,确定性 |
编译器性能之谈
Rust之最大合理之诟病,乃编译之时。至二零二六,犹慢于Go,然显著之改进已至:
# Rust incremental compilation improved dramatically
# First build (cold cache)
$ cargo build --release
# Time: ~45s for a medium project
# Incremental build (one file changed)
$ cargo build --release
# Time: ~8s (was ~35s in 2024)
# rust-analyzer type checking
# VS Code + rust-analyzer gives instant feedback
# Before you even save, you see borrow errors
诀窍:开发时用cargo check(速,无代码生成),cargo build用于最终构建.
Rust之踵疾:编译时日
# For faster iteration, use these settings in .cargo/config.toml
[build]
# Use all CPU cores for linking
rustflags = ["-C", "linker=clang", "-C", "codegen-units=1"]
# Or use mold linker (much faster than default lld)
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
WASM之志:Rust+WASM=生产就绪
Rust者,WebAssembly之首选也:
// math_utils/src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => {
let mut a: u64 = 0;
let mut b: u64 = 1;
for _ in 2..=n {
let temp = a + b;
a = b;
b = temp;
}
b
}
}
}
# Build for WASM
cargo install wasm-pack
wasm-pack build --target web
# 200x faster than JavaScript for Fibonacci
# Smaller binary than comparable C++ WASM
# Zero runtime overhead
Rust之不适者何
诚言:
# Data science / ML
# Python with NumPy/PyTorch is the standard
# Rust bindings exist but ecosystem is fragmented
# Not worth the learning curve for ML work
# Scripts and automation
# Python/Bash/Shell are faster to write
# Rust is overkill for one-off scripts
# Simple CRUD APIs where Go/Python is "good enough"
# Don't use Rust because it's cool
# Use it when you need the performance or safety
学之陡峭之实
# Realistic timeline to productivity in Rust:
Week 1: Fighting the borrow checker constantly
Week 2: Understanding ownership conceptually
Week 3: Writing simple programs without fighting
Month 2: Comfortable with lifetimes in structs
Month 3: Can navigate async Rust and the crate ecosystem
Month 6: Productive Rust developer
# The curve is real but the investment pays off
# Once you internalize ownership, you see memory bugs everywhere in C code
要旨
二〇二六年之 Rust,已堪生产之用:
- 内存安全,不容商榷之系统
- 网络设施(代理、CDN、防火墙)
- WebAssembly 模块(浏览器代码之关键性能)
- 吞吐量高之服务,Go 不足速者
- 欲除尽某类之谬误者
非其时也:
- 速成之模(宜用Python或Go)
- 数理之学(宜用Python)
- 无暇研习之众
非问" Rust已备否?"乃问" Rust合否于尔之用?"
二二六年學鐵或用之?君之經驗何如?












