第一章:欢迎来到Rust的世界 / Chapter 1: Welcome to the World of Rust
你有没有过写C程序到半夜,程序突然崩溃,找了三个小时才发现是野指针的问题?有没有过Java程序在电商大促的时候突然卡顿,查下来是GC Full GC停了2秒,损失了几十万订单?有没有过写Go程序的时候,线上突然出现数据竞争,复现了半天找不到原因?如果你有过这些经历,那你一定会爱上Rust——这门从设计之初就把安全和性能刻进基因里的编程语言。
Have you ever stayed up late writing C programs only to have them crash suddenly, spending three hours debugging before realizing it was a wild pointer issue? Have you ever had a Java program freeze during an e-commerce promotion, only to find out it was a 2-second Full GC pause that cost hundreds of thousands of orders? Have you ever spent ages reproducing a data race bug in a Go program that only appeared in production? If you've had any of these experiences, you'll love Rust — a programming language designed from the ground up with safety and performance baked into its DNA.
---
1.1 Rust的诞生:从电梯故障到安全系统语言 / 1.1 The Birth of Rust: From Elevator Failures to Safe System Languages
Rust的故事要从2006年的一个电梯故障说起。当时Mozilla研究院的工程师Graydon Hoare被困在电梯里20分钟,后来得知故障原因是电梯的控制软件是用C++写的,存在内存错误导致系统崩溃。作为深耕系统级开发多年的工程师,Hoare深受C/C++内存安全问题的困扰:野指针、释放后使用、重复释放、数据竞争……这些问题每年造成全球超过60%的系统级安全漏洞,每年给企业造成超过千亿美元的经济损失(根据2023年Cybersecurity Ventures的统计)。他萌生了一个想法:能不能做一门编程语言,从编译期就彻底杜绝这些内存错误,同时不牺牲C/C++级别的性能?
The story of Rust begins with an elevator failure in 2006. Graydon Hoare, an engineer at Mozilla Research, was trapped in an elevator for 20 minutes, and later learned the fault was caused by memory errors in the elevator's C++ control software. As a veteran system-level developer, Hoare was frustrated by the memory safety issues plaguing C/C++: wild pointers, use-after-free, double-free, data races... These problems account for more than 60% of system-level security vulnerabilities worldwide every year, causing over $100 billion in economic losses to enterprises annually (according to 2023 statistics from Cybersecurity Ventures). He had an idea: what if we could create a programming language that eliminates these memory errors at compile time, without sacrificing the performance of C/C++?
2006年Hoare在Mozilla内部启动了Rust的个人项目,2010年Mozilla官方正式资助Rust的开发,目标是为下一代浏览器引擎Servo打造一门安全、高性能的系统级语言。经过5年的社区迭代,2015年9月Rust 1.0正式发布,标志着语言核心API和语法稳定。2021年Rust基金会正式成立,AWS、谷歌、微软、华为等科技巨头纷纷加入,成为Rust的长期赞助商。根据Stack Overflow连续8年(2016-2023)的开发者调查,Rust连续8年被评为「最受开发者喜爱的编程语言」,2023年Rust的全球使用率已经达到14%,增速位居所有主流语言第一。
Hoare started Rust as a personal project at Mozilla in 2006, and Mozilla officially funded Rust development in 2010, with the goal of building a safe, high-performance system-level language for the next-generation browser engine Servo. After 5 years of community iteration, Rust 1.0 was officially released in September 2015, marking the stabilization of the language's core APIs and syntax. The Rust Foundation was formally established in 2021, with tech giants including AWS, Google, Microsoft and Huawei joining as long-term sponsors. According to Stack Overflow's annual Developer Survey for 8 consecutive years (2016-2023), Rust has been voted the "most loved programming language" for 8 years in a row. In 2023, Rust's global adoption rate has reached 14%, with the fastest growth rate among all mainstream languages.
很多人会问:现在已经有这么多成熟的编程语言了,为什么还要造Rust这个轮子?答案很简单:所有其他主流语言都在「安全」和「性能」之间做了妥协,而Rust是第一个同时做到两者的语言。
Many people ask: there are already so many mature programming languages, why reinvent the wheel with Rust? The answer is simple: all other mainstream languages make trade-offs between "safety" and "performance", while Rust is the first language to deliver both.
---
1.2 主流语言的痛点与Rust的解决方案 / 1.2 Pain Points of Mainstream Languages and Rust's Solutions
要理解Rust的价值,我们首先要看看现在主流语言在系统级开发中的痛点: To understand Rust's value, we first need to look at the pain points of mainstream languages in system-level development:
1.2.1 C/C++:性能之王,安全之殇 / 1.2.1 C/C++: King of Performance, Tragedy of Safety
C/C++是系统级开发的绝对主流,操作系统、数据库、游戏引擎、嵌入式设备几乎都用C/C++开发,性能极强,但内存安全问题一直是挥之不去的阴影: C/C++ is the absolute mainstream for system-level development, used for operating systems, databases, game engines and embedded devices, with extremely strong performance, but memory safety issues have always been a lingering shadow:
- 野指针、释放后使用、重复释放等问题会导致程序崩溃、数据泄露,甚至被黑客利用执行任意代码;
- 多线程环境下的数据竞争问题只能靠开发者手动加锁解决,稍有不慎就会出现难以复现的并发bug;
- 没有包管理器,依赖管理全靠手动,大型项目编译链接复杂到让人头疼。
Wild pointers, use-after-free, double-free and other issues can cause program crashes, data leaks, and even be exploited by hackers to execute arbitrary code; data race issues in multi-threaded environments can only be solved by developers manually adding locks, and a slight mistake can lead to hard-to-reproduce concurrency bugs; there is no package manager, dependency management is all manual, and the compilation and linking of large projects is so complicated that it is a headache.
举个最简单的C语言例子,这段代码编译完全没问题,但运行必崩溃: Take the simplest C language example, this code compiles without any problems, but will definitely crash when running: ```c // C语言:返回栈指针的经典错误 // C language: Classic error of returning a stack pointer int* get_invalid_pointer() { int x = 10; // x在栈上创建,函数结束后自动销毁 return &x; // 返回x的地址,x已经被销毁,地址变成野指针 }
int main() { int* p = get_invalid_pointer(); printf("%d", *p); // 运行时报段错误(Segmentation Fault) return 0; } ``` 而在Rust里,这段代码根本编译不过: But in Rust, this code won't even compile: ```rust // Rust:编译期直接拦截错误 // Rust: Directly block errors at compile time fn get_invalid_pointer() -> &i32 { let x = 10; &x // 编译报错:x的生命周期比返回的引用短 }
fn main() { let p = get_invalid_pointer(); println!("{}", p); } ``` 编译器会直接告诉你:`x`的生命周期太短,返回的引用指向的地址已经被释放了,禁止编译通过。你不需要等到程序跑起来才崩溃,编译阶段就被「安检员」拦住了。 The compiler will directly tell you: the lifetime of `x` is too short, the address pointed to by the returned reference has been released, and compilation is prohibited. You don't have to wait until the program runs to crash, you are stopped by the "security guard" at the compilation stage.
1.2.2 Java/Go:开发效率高,性能和安全的妥协 / 1.2.2 Java/Go: High development efficiency, compromise on performance and safety
Java和Go是现在企业级开发、云原生开发的主流语言,开发效率极高,但为了安全性和易用性,都做了性能上的妥协: Java and Go are the mainstream languages for enterprise development and cloud-native development today, with extremely high development efficiency, but both make compromises on performance for the sake of safety and ease of use:
- **Java**:依赖JVM虚拟机运行,有垃圾回收(GC)机制,虽然解决了内存泄漏问题,但GC的「Stop The World」停顿问题在高并发场景下非常致命:比如电商大促时一次Full GC可能停顿几秒,直接导致订单流失;同时JVM的内存占用比Rust高3-5倍,在嵌入式、边缘计算等资源受限的场景根本无法运行。
- **Go**:自带GC和运行时,开发简单,并发模型友好,但内存安全依然靠运行时检查:比如nil指针panic、数据竞争等问题只能在运行期发现,线上才能爆发;goroutine泄露、channel阻塞等问题也很难提前排查;同时GC的停顿虽然比Java短,但在高频交易、实时渲染等低延迟场景依然无法满足要求。
- **Java**: It relies on the JVM virtual machine to run, with a garbage collection (GC) mechanism. While it solves the problem of memory leaks, the "Stop The World" pause of GC is very deadly in high-concurrency scenarios: for example, a Full GC during an e-commerce promotion may pause for several seconds, directly leading to order loss; at the same time, the memory usage of JVM is 3-5 times higher than that of Rust, which cannot run in resource-constrained scenarios such as embedded devices and edge computing.
- **Go**: It comes with GC and runtime, is simple to develop, and has a friendly concurrency model, but memory safety still relies on runtime checks: for example, nil pointer panics, data races and other issues can only be found during operation, and can only break out online; goroutine leaks, channel blocking and other issues are also difficult to troubleshoot in advance; although the GC pause is shorter than Java, it still cannot meet the requirements of low-latency scenarios such as high-frequency trading and real-time rendering.
举个Go的数据竞争例子,这段代码用`go run -race`运行会检测到数据竞争,但如果不加`-race`参数,运行可能完全正常,线上才会出问题: Take a Go data race example, running this code with `go run -race` will detect the data race, but if you don't add the `-race` parameter, it may run completely normally, and the problem will only appear online: ```go package main
import "fmt"
func main() { count := 0 // 两个goroutine同时修改count,没有加锁 // Two goroutines mo