Rust 简介

设计目标、和 C++/Go 的取舍、以及它不适用的场景。

Beginner
Key PointsRust 的承诺是「零成本抽象」:高级语法不带来运行时开销。

三条设计原则

  1. 内存安全 —— 没有空指针解引用、缓冲区溢出、数据竞争(在安全代码里)
  2. 零成本抽象 —— 迭代器、泛型、trait 编译后和手写循环一样快
  3. 无畏并发 —— 编译期就能挡住数据竞争
Rust
// 迭代器链,编译后等同于一个 for 循环
let sum: i32 = (1..=100)
    .filter(|x| x % 2 == 0)
    .map(|x| x * x)
    .sum();

println!("{}", sum);
Output
171700

和 C++ / Go 比

AspectRustC++Go
内存管理编译期所有权手动 + RAIIGC
内存安全安全代码保证靠人GC 保证
学习曲线陡很陡平缓
编译速度中等慢极快
并发编译期防竞争靠库与经验goroutine 简单
生态成熟度成长中极成熟成熟

一段对比代码

Rust
fn main() {
    let mut v = vec![1, 2, 3];

    // 借用 v 的引用,v 不能同时被改
    let first = &v[0];
    println!("第一个 {}", first);

    // 下面这行会编译失败:cannot borrow `v` as mutable
    // v.push(4);
}
Output
第一个 1

Uncomment v.push(4) and the compiler says cannot borrow v as mutable because it is also borrowed as immutable. That is the borrow checker stopping "read while mutating" before your code ever runs.

不适合的场景

  • 快速原型 —— 编译期的严格会拖慢试错,脚本用 Python 更合适
  • GUI 桌面应用 —— 生态还在早期
  • 机器学习训练 —— 框架基本都在 Python
  • 团队没有系统编程经验 —— 前三个月的产出会明显下降
Rust pays off long term — fewer crashes, stable memory, confident refactors. It costs short term — you write slower. For short projects or unfamiliar teams the trade is poor.

Friends & Partners