Introduction to Rust
Rust is a systems programming language led by Mozilla Research, with memory safety, zero-cost abstraction, and fearless concurrency as its core design goals.
Rust was born in 2006, initially a personal project of Mozilla employee Graydon Hoare, and was later officially sponsored by Mozilla in 2009 with a team formed to develop it.
Rust was originally designed to solve the long-standing pain points of C/C++ in systems programming: memory safety issues (null pointers, dangling pointers, buffer overflows) and the complexity of concurrent programming (data races, deadlocks).

Rust's design philosophy is "eliminating bugs at compile time" -- through a powerful type system and ownership mechanism, the compiler helps you detect memory errors and data races, instead of waiting until runtime to discover problems.
The mascot of the Rust language is a crab named Ferris, friendly and cute, representing the friendly and inclusive culture of the Rust community.
Rust's key design goals can be summarized as follows:
| Design Goal | Description |
|---|---|
| Memory safety (no GC) | Memory safety is guaranteed at compile time through the ownership system, with no garbage collector needed |
| Zero-cost abstractions | High-level language features have no runtime overhead after compilation, with performance equal to hand-written low-level code |
| Fearless concurrency | The type system and ownership rules eliminate data races at compile time |
| Practicality | You can write both operating system kernels and Web applications, covering full-stack scenarios |
| Strong type inference | The compiler automatically infers most types, reducing boilerplate code |
| Rich toolchain | Cargo (package management + build), rustfmt (formatting), and clippy (code checking) work out of the box |
The development history of the Rust language
Rust has gone through nearly twenty years of development, from a personal project to a widely adopted systems language worldwide.
| Time | Version/Event | Description |
|---|---|---|
| 2006 | Personal project | Graydon Hoare began designing the Rust language |
| 2009 | Mozilla sponsorship | Mozilla officially supported Rust development and formed a team |
| 2010 | First public release | The Rust compiler (written in OCaml) was first publicly disclosed at the Mozilla summit |
| 2011 | Self-hosting completed | The Rust compiler was rewritten in Rust itself, dropping the OCaml dependency |
| May 2015 | Rust 1.0 | The first stable version was released, marking that the language was officially ready for production |
| December 2018 | Rust 2018 Edition | The first Edition was released, optimizing the syntax and module system (the NLL borrow checker landed) |
| 2019 | The async ecosystem took shape | The async/await syntax stabilized, and async runtimes such as Tokio matured |
| 2021 | The Rust Foundation was established | AWS, Google, Huawei, Microsoft, and Mozilla jointly established the Rust Foundation |
| October 2021 | Rust 2021 Edition | Introduced improvements such as disjoint capture and IntoIterator for arrays |
| 2022 | Adoption by the Linux kernel | Linux 6.1 officially merged Rust support, making Rust the second language for kernel development |
| February 2024 | Rust 2024 Edition | Further optimized language consistency and developer experience |
The establishment of the Rust Foundation in 2021 was a milestone event. Five technology giants -- AWS, Google, Huawei, Microsoft, and Mozilla -- jointly promised to ensure the long-term independent development of Rust, eliminating the community's worries about "domination by a single company".
Rust adopts a release cadence of one stable version every six weeks, while handling incompatible language changes through the Edition mechanism (released about every 3 years). The same project can mix crates from different Editions, and the compiler guarantees backward compatibility.
Core features of the Rust language
Rust's feature set revolves around the three dimensions of "safety, efficiency, and practicality". The following breaks down Rust's most core language features one by one.
Ownership system (Ownership)
Ownership is Rust's most distinctive and important feature. It manages memory at compile time, with no garbage collector and no manual malloc/free.
Ownership has three major rules:
| Rule | Description | Meaning |
|---|---|---|
| Each value has exactly one owner | A value can be owned by only one variable at a time | Eliminating double-free and dangling pointers |
| When the owner leaves its scope, the value is freed | When a variable leaves its scope, Rust automatically calls drop to free the memory | No need for manual memory management |
| At any moment: either one mutable reference, or multiple immutable references | Reads and writes are mutually exclusive, while reads coexist | Data races are eliminated at compile time |
The intuitive feeling at the code level: when a variable is assigned to another variable, ownership is transferred (move), and the original variable becomes invalid.
Example
fn
main
(
)
{
// s1 takes ownership of the string (the data is stored on the heap)
let
s1
=
String
::
from
(
"Hello, RUNOOB!"
)
;
// ownership moves from s1 to s2, after which s1 is no longer valid
let
s2
=
s1
;
// println!("{}", s1); // compile error! s1 has been moved
println
!
(
"{}"
,
s2
)
;
// correct: s2 is now the owner
// primitive types (stored on the stack) implement the Copy trait, so no move occurs
let
x
=
42
;
let
y
=
x
;
// x is still valid because i32 implements Copy
println
!
(
"x = {}, y = {}"
,
x
,
y
)
;
// both can be used
// immutable references: multiple can exist at the same time
let
s3
=
&
s2
;
// immutable borrow
let
s4
=
&
s2
;
// another immutable borrow, allowed
println
!
(
"s3 = {}, s4 = {}"
,
s3
,
s4
)
;
// mutable references: only one can exist at a time
let
mut
data
=
String
::
from
(
"runoob"
)
;
let
r
=
&
mut
data
;
// mutable borrow
r.push_str
(
"!"
)
;
// modify the original value through the mutable reference
println
!
(
"After modification: {}"
,
r
)
;
// the scopes of s3 and s4 have ended, so a mutable reference can be created
}
The ownership system is the "steep slope" of the Rust learning curve. Beginners often "fight" with the compiler, but once you understand it, you will find that those errors blocked by the compiler could be fatal runtime bugs in C/C++.
Pattern matching (Pattern Matching)
Rust's match expression is extremely powerful; the compiler exhaustively checks all cases to ensure no branch is missed.
Example
fn
main
(
)
{
// match with numbers
let
score
=
85
;
match
score
{
90
..
=
100
=>
println
!
(
"RUNOOB rating: A"
)
,
// range matching
60
..
=
89
=>
println
!
(
"RUNOOB rating: B"
)
,
0
..
=
59
=>
println
!
(
"RUNOOB rating: C"
)
,
_
=>
println
!
(
"Invalid score"
)
,
// wildcard, matching all remaining cases
}
// match destructuring a tuple
let
pair
=
(
3
,
7
)
;
match
pair
{
(
0
,
y
)
=>
println
!
(
"The first is 0, the second is {}"
,
y
)
,
(
x
,
0
)
=>
println
!
(
"The first is {}, the second is 0"
,
x
)
,
(
x
,
y
)
=>
println
!
(
"Two values: {} and {}"
,
x
,
y
)
,
}
}
Enums and Option/Result
Rust's enums (enum) can carry data, and when used with match they enable safe and highly expressive control flow.
Option in the standard library
Example
use
std
::
fs
;
fn
main
(
)
{
// Option
let
numbers
=
vec
!
[
10
,
20
,
30
]
;
let
first
=
numbers.get
(
0
)
;
// returns Option<&i32>
let
missing
=
numbers.get
(
5
)
;
// returns Option<&i32>
match
first
{
Some
(
&
val
)
=>
println
!
(
"First element: {}"
,
val
)
,
None
=>
println
!
(
"not found"
)
,
}
// a more concise way: if let
if
let
Some
(
&
val
)
=
missing
{
println
!
(
"Found: {}"
,
val
)
;
}
else
{
println
!
(
"Index 5 does not exist"
)
;
// expected to take this branch
}
// Result
let
content
=
fs
::
read_to_string
(
"config.txt"
)
;
match
content
{
Ok
(
text
)
=>
println
!
(
"File contents: {}"
,
text
)
,
Err
(
e
)
=>
println
!
(
"Read failed: {}"
,
e
)
,
}
}
Rust has no null value and no try-catch exception mechanism. Option and Result are handled mandatorily at compile time -- if you forget to check, the code will not compile. This fundamentally eliminates null pointer exceptions and uncaught exceptions.
Zero-cost abstractions
Rust's high-level features (iterators, closures, generics) are completely equivalent to hand-written low-level loops after compilation, producing no extra runtime overhead.
This means you can write code in a functional-like style while getting the same high performance as C.
Example
fn
main
(
)
{
let
data
=
vec
!
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
;
// chained iterator calls -- look like high-level abstractions
// after compilation they expand into machine code equivalent to a hand-written for loop
let
result
:
Vec
<
i32
=
data
.iter
(
)// Get the iterator
.filter
(
|&
x
|
x
%
2
==
0
)
// filter even numbers
.map
(
|&
x
|
x
x
)
// square
.collect
(
)
;
// collect into a Vec
println
!
(
"{:?}"
,
result
)
;
// [4, 16, 36, 64, 100]
}
Fearless concurrency (Fearless Concurrency)
Rust's type system and ownership rules eliminate data races at compile time. The Send and Sync traits automatically mark whether a type can be safely transferred or shared between threads.
If you try to share non-thread-safe data across multiple threads, the compiler will report an error directly -- instead of waiting until production runtime for strange concurrency bugs to appear.
Example
use
std
::
sync
::
{
Arc
,
Mutex
}
;
use
std
::
thread
;
fn
main
(
)
{
// Arc (atomic reference counting) is used to share ownership among multiple threads
// Mutex provides mutually exclusive access
let
counter
=
Arc
::
new
(
Mutex
::
new
(
0
)
)
;
let
mut
handles
=
vec
!
[
]
;
for
i
in
0
..
10
{
// clone the Arc so each thread holds a reference to the same data
let
counter
=
Arc
::
clone
(
&
counter
)
;
let
handle
=
thread
::
spawn
(
move
||
{
// lock() acquires the mutex, returning a MutexGuard
let
mut
num
=
counter.lock
(
)
.unwrap
(
)
;
num
+=
1
;
// modify the inner value through dereferencing
println
!
(
"Thread {} finished accumulating, current value: {}"
,
i
,
num
)
;
}
)
;
handles.push
(
handle
)
;
}
// Wait for all threads to finish
for
handle
in
handles
{
handle.join
(
)
.unwrap
(
)
;
}
println
!
(
"Final count: {}"
,
counter.lock
(
)
.unwrap
(
)
)
;
}
Cargo: an integrated build tool
Cargo is Rust's official package manager and build system, integrating dependency management, compilation, testing, documentation generation, and publishing.
Compared with the fragmented experience in the C/C++ ecosystem where you need to manually configure CMake/Makefile and package managers, Cargo provides an "out-of-the-box" integrated experience.
| Command | Function | Typical scenario |
|---|---|---|
| cargo new project | Creating a new project | Initialize a project, automatically generating Cargo.toml and src/main.rs |
| cargo build | Compile the project (debug mode) | Develop and debug |
| cargo build --release | Compile the project (optimized mode) | Production release, enabling all compiler optimizations |
| cargo run | Compile and run | Quickly test code |
| cargo test | Running tests | Unit tests, integration tests, doc tests |
| cargo check | Quickly check whether the code compiles (without producing a binary) | Real-time syntax checking in the IDE |
| cargo doc --open | Generate and open documentation | Browse the API documentation of dependencies |
| cargo clippy | Code style checking (lint) | Find discouraged patterns and potential problems |
| cargo fmt | Code Formatting | Unify code style |
| cargo publish | Publish to crates.io | Publish an open-source library |
cargo check is a very useful command in development. It only checks syntax and types, does not generate an executable, and is much faster than cargo build. Most IDE Rust plugins automatically run cargo check when you save a file.
Application areas of the Rust language
Thanks to the advantages of memory safety and high performance, Rust is rapidly expanding in many fields.
Systems programming and high-performance servers
This is Rust's "home turf" -- suitable for scenarios requiring extreme performance and high memory safety. The async runtime Tokio and Web frameworks Actix Web and Axum perform excellently in high-concurrency scenarios.
WebAssembly
Rust is one of the best languages for compiling to WebAssembly. Its zero-cost abstractions and no-GC nature make Wasm artifacts small in size and high in performance.
The front-end frameworks Yew and Leptos allow writing SPA applications in Rust. Figma, Cloudflare Workers, and others heavily use Rust + Wasm in production.
Embedded systems and IoT
Rust's no_std mode allows running on bare metal without an operating system, suitable for resource-constrained devices such as MCUs and sensors.
RTIC (a real-time interrupt-driven concurrency framework) and Embassy (an async embedded framework) are representative projects of embedded Rust.
CLI tools
Rust compiles to standalone binaries with excellent performance, resulting in many star CLI tools:
| Tool | Function | Replacement target |
|---|---|---|
| ripgrep (rg) | Extremely fast code search | grep |
| fd | Fast file search | find |
| bat | File viewing with syntax highlighting | cat |
| delta | Syntax-highlighted Git diff | git diff |
| zoxide | Smart directory jumping | cd |
| dust | Disk space analysis | du |
Blockchain and Web3
Rust has an important position in the blockchain field. The core of the Solana chain is written in Rust, and new public chains such as Sui, Aptos, and Polkadot (Substrate) also use Rust as their main development language.
Databases and data infrastructure
High-performance databases and data processing systems are Rust's strong suit: TiKV (distributed KV storage, the storage layer of TiDB), SurrealDB, Polars (a DataFrame library), Databend (a cloud data warehouse), and others are all built with Rust.
Operating systems and infrastructure
Rust has entered the Linux kernel (6.1+), Google uses Rust in Android to rewrite the Bluetooth and Wi-Fi stacks, and Microsoft also uses Rust in the Windows kernel to rewrite some components.
On the hobbyist side, Redox OS is a Unix-like operating system written entirely from scratch in Rust.
Quick Start
Rust officially provides a very convenient installation tool, rustup, which sets up the compiler, package manager, and documentation with one command.
Installing Rust
# Unix/macOS
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Verify installation
$ rustc --version
rustc 1.85.0 (4d91de4e4 2025-02-17)
$ cargo --version
cargo 1.85.0
The first Rust program
Using Cargo to create a project is the most recommended approach; it automatically generates a standard project structure.
# Create new project
$ cargo new hello_runoob
Created binary (application) `hello_runoob` package
# Project structure
hello_runoob/
├── Cargo.toml # 项目元数据和依赖配置
└── src/
└── main.rs # 程序入口文件
Cargo.toml is the project's configuration file, similar to Node.js's package.json:
Example
[
package
]
name =
"hello_runoob"
Package name (required, separated by underscores)
version =
"0.1.0"
Version number (required, following semantic versioning)
edition =
"2024"
Rust Edition (required, affects language syntax rules)
[
dependencies
]
Declare project dependencies here, for example:
serde = { version = "1.0", features = ["derive"] }
The default generated main.rs contains the simplest Hello World program:
Example
// File path: src/main.rs
// Rust program entry point: every executable program must have a main function
fn
main
(
)
{
// println! is a macro (note the ! symbol after it)
// macros expand into more complex code at compile time
println
!
(
"Hello, RUNOOB!"
)
;
println
!
(
"Welcome to the world of the Rust language"
)
;
}
# Compile and run
$ cargo run
Compiling hello_runoob v0.1.0
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.52s
Running `target/debug/hello_runoob`
Hello, RUNOOB!
欢迎来到 Rust 语言的世界
Overview of basic syntax
Rust's syntax draws on the strengths of functional and systems languages. The following is a quick tour of the most commonly used syntax elements, with each example being a complete program that can be run directly.
Variables and mutability
Variables in Rust are immutable by default. This forces developers to explicitly mark which data will change, making the code's intent clearer and making it easier for the compiler to optimize.
Example
fn
main
(
)
{
// immutable variable (default): cannot be reassigned after declaration
let
name
=
"RUNOOB"
;
// name = "other"; // compile error! an immutable variable cannot be reassigned
println
!
(
"Name: {}"
,
name
)
;
// mutable variable: explicitly declared with the mut keyword
let
mut
score
=
0
;
println
!
(
"Initial score: {}"
,
score
)
;
score
=
100
;
// can be modified
println
!
(
"Updated score: {}"
,
score
)
;
// variable shadowing: redeclare a variable with the same name using let
let
x
=
5
;
let
x
=
x
1
;
// the new variable x shadows the old x, with a value of 6
let
x
=
x
2
;
// shadowed again, with a value of 12
println
!
(
"Final value of x: {}"
,
x
)
;
// constant: determined at compile time, type must be annotated, naming convention uses all uppercase
const
MAX_POINTS
:
u32
=
100
_000
;
println
!
(
"Maximum points: {}"
,
MAX_POINTS
)
;
}
Variable shadowing and mut are not the same thing. Shadowing uses let to redeclare a new variable with the same name and can change the type; while mut only allows the same variable to modify its value, with the type unchanged.
Basic Data Types
Rust is a statically typed language, and the compiler must know the types of all variables at compile time.
| Category | Type | Example | Description |
|---|---|---|---|
| Signed integers | i8, i16, i32, i64, i128, isize | let x: i32 = -42; | The default integer type is i32 |
| Unsigned integers | u8, u16, u32, u64, u128, usize | let y: u64 = 100; | usize is used for indexing and lengths |
| Float (floating point number) | f32, f64 | let pi: f64 = 3.14; | The default floating-point type is f64 |
| Boolean | bool | let ok: bool = true; | true or false |
| Character | char | let c = 'R'; | 4 bytes, representing a Unicode scalar value |
| Tuple | (T1, T2, ...) | let t: (i32, f64) = (10, 3.14); | Fixed length, types may differ |
| arrays | [T; N] | let a: [i32; 3] = [1, 2, 3]; | Fixed length, same type, allocated on the stack |
| Slicing | &[T] | let s: &[i32] = &a[..]; | A reference view of an array or Vec |
| Dynamic array | Vec |
let v: Vec |
Variable length, allocated on the heap |
| String | String / &str | let s = String::from("hi"); | String is modifiable, &str is a reference |
Control flow
Rust's control flow includes if, loop, while, for, and match. Among them, if and loop can be used as expressions that return values.
Example
fn
main
(
)
{
let
score
=
75
;
// if is an expression that can return a value (each branch must return the same type)
let
grade
=
if
score
=
90
{
"A"
}
else
if
score
=
60
{
"B"
}
else
{
"C"
}
;
println
!
(
"RUNOOB rating: {}"
,
grade
)
;
// loop is an infinite loop (exit with break, which can carry a return value)
let
mut
count
=
0
;
let
result
=
loop
{
count
+=
1
;
if
count
==
5
{
break
count
2
;
// break followed by a value, used as the return value of loop
}
}
;
println
!
(
"loop return value: {}"
,
result
)
;
// while conditional loop
let
mut
n
=
3
;
while
n
0
{
println
!
(
"Countdown: {}"
,
n
)
;
n
-=
1
;
}
// for in iteration (most commonly used)
let
items
=
[
"apple"
,
"banana"
,
"cherry"
]
;
for
(
i
,
item
)
in
items.iter
(
)
.enumerate
(
)
{
println
!
(
"No. {}: {}"
,
i
1
,
item
)
;
}
// for in range iteration
for
num
in
1
..
=
3
{
// 1..=3 means 1, 2, 3 (both ends included)
println
!
(
"Number: {}"
,
num
)
;
}
}
function
Rust functions are declared with the fn keyword, and parameters and return values must have explicitly annotated types. The value of the last expression is the return value (no return keyword needed).
Example
// ordinary function: takes two i32 values and returns their sum
fn
add
(
a
:
i32
,
b
:
i32
)
->
i32
{
a
b
// the last expression is automatically the return value (note there is no semicolon at the end)
}
// multiple return values: use a tuple to return multiple values
fn
divide
(
a
:
f64
,
b
:
f64
)
->
(
f64
,
String
)
{
if
b
==
0.0
{
return
(
0.0
,
String
::
from
(
"Error: division by zero is not allowed"
)
)
;
}
(
a
/
b
,
String
::
from
(
"OK"
)
)
// return a tuple
}
// generic function: use a trait bound to constrain the behavior of the type parameter
fn
largest
<
T
:
PartialOrd
(
list
:
&
[
T
]
)
->
&
T
{
let
mut
largest
=
&
list
[
0
]
;
for
item
in
list
{
if
item
largest
{
largest
=
item
;
}
}
largest
}
fn
main
(
)
{
// call the ordinary function
let
sum
=
add
(
10
,
20
)
;
println
!
(
"10 + 20 = {}"
,
sum
)
;
// call the multiple-return-value function
let
(
result
,
msg
)
=
divide
(
10.0
,
2.0
)
;
println
!
(
"10 / 2 = {} ({})"
,
result
,
msg
)
;
// the division-by-zero case
let
(
result
,
msg
)
=
divide
(
10.0
,
0.0
)
;
println
!
(
"10 / 0 = {} ({})"
,
result
,
msg
)
;
// call the generic function
let
nums
=
vec
!
[
3
,
7
,
2
,
9
,
5
]
;
println
!
(
"RUNOOB maximum: {}"
,
largest
(
&
nums
)
)
;
}
Structs and impl blocks
Rust uses struct to define data structures and impl blocks to implement methods for structs. This is similar to Go's way of defining methods, but more compact in language organization.
Example
// define a struct (similar to C's struct, but more powerful)
struct
User
{
name
:
String
,
// String type, owning the data
:
String
,
active
:
bool
,
login_count
:
u64
,
// u64 unsigned 64-bit integer
}
// the impl block implements methods for User
impl
User
{
// associated function (similar to a static method): create a new instance
fn
new
(
name
:
String
,
:
String
)
->
User
{
User
{
name
,
,
active
:
true
,
// Default value
login_count
:
0
,
// Default value
}
}
// Methods: &self represents an immutable reference to the instance
fn
summary
(
&
self
)
->
String
{
format
!
(
"{} ({}) - Login count: {}"
,
self
.name
,
self
,
self
.login_count
)
}
// Methods: &mut self represents a mutable reference to the instance
fn
login
(
&
mut
self
)
{
self
.login_count
+=
1
;
}
}
fn
main
(
)
{
// Create an instance using an associated function
let
mut
user
=
User
::
new
(
String
::
from
(
"runoob"
)
,
String
::
from
(
"runoob@example.com"
)
,
)
;
println
!
(
"{}"
,
user.summary
(
)
)
;
// Simulate login
user.login
(
)
;
user.login
(
)
;
println
!
(
"Logged in {} times"
,
user.login_count
)
;
}
Common examples
The following two complete examples, close to real-world scenarios, demonstrate typical usage of Rust in practical development.
Building an HTTP API service
Use the Axum framework (based on the Tokio async runtime) to build an HTTP API with JSON responses.
First, add dependencies in Cargo.toml:
# Cargo.toml
[dependencies]
axum = "0.8" # Web 框架
tokio = { version = "1", features = ["full"] } # 异步运行时
serde = { version = "1", features = ["derive"] } # 序列化
serde_json = "1" # JSON 支持
Example
// File path: src/main.rs
use
axum
::
{
extract
::
Query
,
response
::
Json
,
routing
::
get
,
Router
,
}
;
use
serde
::
{
Deserialize
,
Serialize
}
;
use
std
::
collections
::
HashMap
;
// Request parameter struct (deserialization)
[
derive
(
Deserialize
)
]
struct
HelloParams
{
name
:
Option
<
String
,// Option indicates optional parameters
}
// Response struct (serialization)
[
derive
(
Serialize
)
]
struct
ApiResponse
{
code
:
u16
,
message
:
String
,
data
:
Option
<
HashMap
<
String
,
String
,// Optional data field
}
// Handle GET /hello request
// Query(HelloParams) automatically extracts name from URL query parameters
async
fn
hello_handler
(
Query
(
params
)
:
Query
<
HelloParams
)
->
Json
<
ApiResponse
{
let
name
=
params.name.unwrap_or_else
(
||
String::
from
(
"RUNOOB"
)
)
;
let
mut
data
=
HashMap
::
new
(
)
;
data.insert
(
"name"
.to_string
(
)
,
name.clone
(
)
)
;
Json
(
ApiResponse
{
code
:
200
,
message
:
format
!
(
"Hello, {}! Welcome to the Rust HTTP service"
,
name
)
,
data
:
Some
(
data
)
,
}
)
}
// The #[tokio::main] macro transforms async fn main into a Tokio runtime
[
tokio
::
main
]
async
fn
main
(
)
{
// Build routes
let
app
=
Router
::
new
(
)
.route
(
"/hello"
,
get
(
hello_handler
)
)
;
// Bind address and start the service
let
listener
=
tokio
::
net
::
TcpListener
::
bind
(
"0.0.0.0:8080"
)
.await
.unwrap
(
)
;
println
!
(
"RUNOOB server started, listening at: http://localhost:8080"
)
;
println
!
(
"Example access: http://localhost:8080/hello?name=Rustdeveloper"
)
;
axum
::
serve
(
listener
,
app
)
.await.unwrap
(
)
;
}
$ cargo run
RUNOOB 服务器启动,监听地址: http://localhost:8080
访问示例: http://localhost:8080/hello?name=Rust开发者
# Test with curl
$ curl http://localhost:8080/hello?name=Rust开发者
{"code":200,"message":"你好,Rust开发者!欢迎访问 Rust HTTP 服务","data":{"name":"Rust开发者"}}
$ curl http://localhost:8080/hello
{"code":200,"message":"你好,RUNOOB!欢迎访问 Rust HTTP 服务","data":{"name":"RUNOOB"}}
Axum is one of the most popular web frameworks in the Rust ecosystem, maintained by the Tokio team. It makes full use of Rust's type system, checking operations such as route parameter extraction and state sharing at compile time, greatly reducing runtime errors.
Batch file processing tool
This is a CLI tool close to a real-world scenario: recursively traverse directories, count the lines and size of all files, and summarize by extension.
Add dependencies in Cargo.toml:
# Cargo.toml
[dependencies]
walkdir = "2" # 递归遍历目录
Example
// File path: src/main.rs
use
std
::
collections
::
HashMap
;
use
std
::
fs
;
use
walkdir
::
WalkDir
;
// Third-party library for recursively traversing directories
fn
main
(
)
{
let
path
=
"."
;
// Start scanning from the current directory
// Statistics: grouped by file extension
// HashMap
let
mut
stats
:
HashMap
<
String
,
(
usize
,
usize
,
u64
)
=
HashMap::
new
(
)
;
// WalkDir recursively traverses directories, automatically skipping hidden files and .git directories
for
entry
in
WalkDir
::
new
(
path
)
.into_iter
(
)
.filter_map
(
|
e
|
e.ok
(
)
)
// Filter out inaccessible entries
.filter
(
|
e
|
e.file_type
(
)
.is_file
(
)
)
// Only process files
{
// Get the file extension
let
ext
=
entry
.path
(
)
.extension
(
)
.and_then
(
|
e
|
e.to_str
(
)
)
.unwrap_or
(
"(no extension)"
)
.to_lowercase
(
)
;
// Read file contents (text files only; binary files may be garbled but won't affect statistics)
if
let
Ok
(
content
)
=
fs
::
read_to_string
(
entry.path
(
)
)
{
let
line_count
=
content.lines
(
)
.count
(
)
;
let
size
=
entry.metadata
(
)
.map
(
|
m
|
m.len
(
)
)
.unwrap_or
(
0
)
;
let
(
count
,
lines
,
total_size
)
=
stats.entry
(
ext
)
.or_insert
(
(
0
,
0
,
0
)
)
;
count
+=
1
;
lines
+=
line_count
;
total_size
+=
size
;
}
}
// Sort by file count in descending order and output
let
mut
sorted
:
Vec
<
_
=
stats.into_iter
(
)
.collect
(
);
sorted.sort_by
(
|
a
,
b
|
b.1
.0
.cmp
(
&
a.1
.0
)
)
;
println
!
(
"=== RUNOOB Directory File Statistics ==="
)
;
println
!
(
"{:<15} {:>8} {:>10} {:>12}"
,
"Extension"
,
"File count"
,
"Total lines"
,
"Total size (bytes)"
)
;
println
!
(
"{}"
,
"-"
.repeat
(
50
)
)
;
for
(
ext
,
(
count
,
lines
,
size
)
)
in
&
sorted
{
println
!
(
"{:<15} {:>8} {:>10} {:>12}"
,
ext
,
count
,
lines
,
size
)
;
}
}
$ cargo run --release
=== RUNOOB 目录文件统计 ===
扩展名 文件数 总行数 总大小(bytes)
--------------------------------------------------
rs 12 856 28432
toml 3 45 1534
md 2 120 3412
html 1 510 14256
(无扩展名) 1 8 210
Common tools and commands quick reference
Besides Cargo's built-in features, the Rust ecosystem provides a series of tools that improve development efficiency:
| Command | Function | Description |
|---|---|---|
| rustup update | Update the Rust toolchain | Upgrade rustc, cargo, etc. to the latest stable version |
| rustup component add rustfmt | Install the code formatting tool | Automatically format code on save |
| rustup component add clippy | Install the code checking tool | Discover discouraged patterns and potential bugs |
| rustup doc | Open local documentation | View the standard library and The Book offline |
| cargo add |
Add Dependency | Automatically edit Cargo.toml and fetch the latest versions |
| cargo update | Update dependency versions | Update Cargo.lock according to the version constraints in Cargo.toml |
| cargo tree | View the dependency tree | Visualize the complete dependency relationships of a project |
| cargo bench | Run benchmark tests | Measure code performance |
| cargo install |
Install CLI tools written in Rust | such as cargo install ripgrep |
Notes and common issues
The following are the challenges most commonly faced by Rust beginners and recommendations for best practices.
It's normal to "fight" with the compiler
Rust's learning curve is widely recognized as steep at first and easier later. Ownership and borrowing checks are the biggest obstacles for beginners.
When your code is repeatedly rejected by the compiler, don't be discouraged—this precisely shows the compiler is helping you catch potential runtime bugs. As you gain experience, you'll gradually get used to thinking the Rust way, and the compiler will become your most reliable partner rather than an enemy.
The difference between String and &str
This is the concept most easily confused by Rust beginners. String is an owned, heap-allocated string (modifiable), while &str is an immutable reference to string data (a borrowed view), usually obtained via automatic dereferencing of &String.
Example
fn
main
(
)
{
// String: owned, modifiable, on the heap
let
mut
s
=
String
::
from
(
"Hello"
)
;
// &str: reference, not modifiable, usually used as function parameters
let
slice
:
&
str
=
"RUNOOB"
;
// String literals are themselves &str
s.push_str
(
", world!"
)
;
// String can be modified
println
!
(
"{}"
,
s
)
;
println
!
(
"{}"
,
slice
)
;
// Choosing &str (rather than String) for function parameters is more flexible
greet
(
"RUNOOB"
)
;
// You can pass &str directly
greet
(
&
s
)
;
// You can also automatically convert from &String to &str
}
fn
greet
(
name
:
&
str
)
{
println
!
(
"Hello, {}!"
,
name
)
;
}
Error handling: panic! vs Result
Rust distinguishes unrecoverable errors (using panic!, which terminates the program) from recoverable errors (using Result, where the caller decides how to handle them).
In library code, you should return Result rather than panic!, giving the caller a choice. In application code, you can decide based on the specific situation.
unsafe: use with caution but necessary
Rust provides the unsafe keyword, allowing low-level operations such as raw pointer manipulation and calling external functions (FFI).
unsafe does not mean "disabling safety checks"; rather, it lets developers take responsibility for the part of safety that the compiler cannot automatically guarantee. Most application code doesn't need unsafe—if you find yourself using it frequently, your design may need adjustment.
Long compilation time
Rust is known for long compilation times, especially for large projects. This is because the compiler performs extensive checks (ownership analysis, lifetime verification, trait resolution, etc.) and optimizations at compile time.
Mitigations: use cargo check instead of cargo build for daily development; split large crates into sub-crates to leverage incremental compilation; use sccache to cache compilation results; upgrade hardware (especially SSDs and more CPU cores).
Suggested Learning Path
For Rust beginners, the following learning order is recommended:
- Read through The Rust Programming Language(the official book, free), focusing on understanding the ownership chapter
- Read and write simultaneously on the Rust Playground (play.rust-lang.org) for immediate compiler feedback
- Pass Rustlings Do small exercises to consolidate syntax
- Read Rust by Example, learn through examples
- Try rewriting a small project you're familiar with in Rust, understanding Rust's design trade-offs through practice
Summary
With three core advantages—memory safety (no GC), zero-cost abstractions, and fearless concurrency—Rust occupies a unique ecological niche in areas such as systems programming, high-performance services, WebAssembly, and blockchain.
Although the learning curve is steep, the compiler's strict checks translate into extremely high code quality and maintainability in long-term projects—which is why more and more companies and open-source projects choose Rust.
Rust's advantages and applicable scenarios are summarized below:
| Dimension | Rust's performance |
|---|---|
| Learning curve | Relatively steep (the ownership system needs understanding and adaptation), but concepts are stable and beneficial for life once learned |
| Compilation Speed | Relatively slow (lots of compile-time checks), but mitigated by cargo check and incremental compilation |
| Runtime performance | On par with C/C++, far exceeding languages with GC |
| Memory Safety | Guaranteed at compile time, no GC needed, no null pointers, dangling pointers, or buffer overflows |
| Concurrency safety | Data races eliminated at compile time, fearless concurrency |
| Ecosystem maturity | Rapidly growing, already very mature in systems programming, WebAssembly, and blockchain |
| Best suited for | Systems programming, high-performance backends, WebAssembly, embedded systems, blockchain, CLI tools, databases |
| Less suited for | Rapid prototyping (compilation time), GUI desktop applications, game development (compared to mature engines) |