Rust: Introduction to Rust and Setting Up the Development…
Rust is a language that empowers everyone to build reliable and efficient software—it has no garbage collection, yet guarantees memory safety.
This tutorial is intended for developers who have a basic understanding of at least one programming language. Whether you come from a C/C++, Java, Python, or JavaScript background, Rust's ownership system and zero-cost abstractions will reshape your understanding of "safety." Rust has been voted the "most loved programming language" in the Stack Overflow Developer Survey for several years in a row.
1. What You'll Learn
- What Is Rust? Its Core Design Philosophy
- Differences Between Rust and C/C++/Go, and Their Appropriate Use Cases
- Install Rust on Windows, macOS, or Linux using rustup
- Create, build, and run projects with Cargo
- Write and run your first Rust program
- The Rust ecosystem (crates.io and the standard library)
2. The Story of a Systems Programmer
(1) Agony: The Nightmare of the C Language
Tom is an embedded systems engineer. One day, he was assigned an urgent task:
"Reduce the memory usage of this web service from 300MB to less than 50MB, while ensuring it never crashes."
He developed it in C and found that:
- Manually managing memory results in over 30 instances of
mallocandfreein the code; if you fix one, you might forget another. - Null pointer caused the online service to crash twice a week, and I was woken up in the middle of the night to fix it
- Buffer overflow—the security team called to say, "There's a risk of a remote attack."
- Writing tests? With C, you have to set up your own testing framework, and it takes two days to get CI up and running.
What did he end up choosing? He switched to Rust.
(2) The Rust Solution
For the same task, Tom wrote the following in Rust:
fn main() {
let msg = String::from("Hello, secure world!");
// Compiler Guarantees: msg memory is automatically released when it goes out of scope.
// Not necessary malloc, nor free
println!("{}", msg);
}
Total time: Compiles successfully = Safe. The Rust compiler detects memory errors during compilation. No Valgrind, no Sanitizer—if it compiles, it's safe.
That's the beauty of Rust: eliminating memory errors at compile time with zero runtime overhead. Its design philosophy is that "safety isn't achieved through developer caution, but is guaranteed by the compiler."
3. What is Rust?
Rust is a system-level programming language created in 2015 by Mozilla researcher Graydon Hoare, originally designed for the Firefox browser engine.
(1) Rust's Three Core Principles
graph LR
A[Rust Three Major Commitments] --> B[Zero-Cost Abstraction]
A --> C[Memory Safety]
A --> D[Concurrency-Safe]
B --> E[Expressiveness of High-Level Languages<br>Assembly-Level Performance]
C --> F[Ownership + Borrow<br>Eliminating Memory Errors at Compile Time]
D --> G[Send+Sync trait<br>Data race detected at compile time]
| Category | Description |
|---|---|
| Zero-Cost Abstraction | The expressiveness of high-level languages, the performance of assembly. No runtime overhead |
| Memory Safety Guarantees | Ownership + Borrowing + Lifecycle; the compiler guarantees at compile time that there are no null pointers, no wild pointers, and no data races |
| Fearless Concurrency | The Send and Sync traits allow concurrency errors to be detected at compile time |
(2) Rust vs C/C++ vs Go
| Dimension | C/C++ | Go | Rust |
|---|---|---|---|
| Memory Management | Manual malloc/free | GC (Garbage Collection) | Ownership + Borrowing Checks (Compile-Time) |
| Performance | Very high | High (with GC pauses) | Very high (zero runtime) |
| Security Commitment | None (depends on programmers) | Partial (GC prevents memory leaks) | Complete (guaranteed at compile time) |
| Concurrency Model | pthreads (manual) | goroutine + channel | std::thread + Send/Sync trait |
| Package Management | Makefile / CMake | go mod | Cargo (out of the box) |
| Learning Curve | Medium-High (pointers can be off-putting) | Low | Medium-High (borrow checker) |
4. Install Rust
(1) Install using rustup
The recommended way to install Rust is through rustup, a Rust version management tool.
# Run in the terminal (Windows requires Visual Studio C++ Build Tools to be installed first)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
After installation, verify the version:
rustc --version # Output: rustc 1.86.0 (05f9846f8 2025-03-31)
cargo --version # Output: cargo 1.86.0 (version number)
(2) Special Notes for Windows
Windows users must first install Visual Studio Build Tools (or Visual Studio 2019 or later) and select the "Desktop development with C++" workload. Rust relies on the MSVC linker.
(3) Updating and Uninstalling
rustup update # Update to the latest version
rustup self uninstall # Uninstall (for cache retention, use uninstall rather than directly deleting the directory)
5. Your First Rust Program
▶ Example 1: Hello World (Difficulty ⭐)
// ============================================
// First Rust Program: Print Hello World
// ============================================
fn main() {
println!("Hello, world!");
}
Output:
Hello, world!
fn main()is the entry point for every Rust program.println!is a macro (note!) used to print text to the terminal.
▶ Example 2: Creating a Project with Cargo (Difficulty ⭐)
# Create a New Project
cargo new hello_cargo
cd hello_cargo
cargo new will generate the following structure:
hello_cargo/
├── Cargo.toml # Project Configuration File (Dependencies, Metadata)
├── src/
│ └── main.rs # Source Code Entry Point
Cargo.toml Content:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
Compile and run:
cargo build # Compilation (generates target/debug/ directory)
cargo run # Compilation + Run
Output:
Hello, world!
Cargo is Rust's package manager and build system.
cargo buildGenerates a debug build;cargo runcompiles and runs with a single command;cargo checkperforms a syntax check only without generating a binary (faster).
▶ Example 3: Simple Calculator (Difficulty ⭐⭐)
// ============================================
// A Simple Addition Calculator
// ============================================
fn main() {
let a: i32 = 10; // i32 is a 32-bit signed integer
let b: i32 = 20; // Rust type annotations use a colon
let sum = a + b;
println!("{} + {} = {}", a, b, sum);
}
Output:
10 + 20 = 30
Output:
=== City Temperature Report ===
Variables in Rust are immutable by default. Here, they are declared using
let; if you need to modify their values later, you must uselet mut. Type annotations: i32are optional—the compiler can infer the type from context.
▶ Example 4: Comprehensive Exercise—Temperature Conversion and Reporting (Difficulty ⭐⭐)
Output:
=== City Temperature Report ===
City Celsius(°C) Fahrenheit(°F)
<"-".repeat(34)>
Beijing 28.5 <f>
Freezing Point: 32.0°F = <freezing_c>°C
// ============================================
// Comprehensive Example: Temperature Conversion + Simple Report Generation
// Demo Variables, Types, Basic Syntax, Such as Formatted Output
// ============================================
fn celsius_to_fahrenheit(celsius: f64) -> f64 {
celsius * 9.0 / 5.0 + 32.0
}
fn fahrenheit_to_celsius(fahrenheit: f64) -> f64 {
(fahrenheit - 32.0) * 5.0 / 9.0
}
fn main() {
let cities = ["Beijing", "Shanghai", "Guangzhou"];
let temps_c = [28.5, 31.2, 33.8];
println!("=== City Temperature Report ===");
println!("{:<12} {:>10} {:>10}", "City", "Celsius(°C)", "Fahrenheit(°F)");
println!("{}", "-".repeat(34));
let mut index = 0;
while index < cities.len() {
let c = temps_c[index];
let f = celsius_to_fahrenheit(c);
println!("{:<12} {:>10.1} {:>10.1}", cities[index], c, f);
index += 1;
}
let freezing_f: f64 = 32.0;
let freezing_c = fahrenheit_to_celsius(freezing_f);
println!("\nFreezing Point: {:.1}°F = {:.1}°C", freezing_f, freezing_c);
const BOILING_C: f64 = 100.0;
let boiling_f = celsius_to_fahrenheit(BOILING_C);
println!("Boiling Point: {:.1}°C = {:.1}°F", BOILING_C, boiling_f);
}
Output:
=== City Temperature Report ===
City Celsius(°C) Fahrenheit(°F)
----------------------------------
Beijing 28.5 83.3
Shanghai 31.2 88.2
Guangzhou 33.8 92.8
Freezing Point: 32.0°F = 0.0°C
Boiling Point: 100.0°C = 212.0°F
This comprehensive example covers function definitions, constant declarations, array iteration, formatted output, and temperature conversion formulas, providing a complete walkthrough of Rust's basic syntax.
▶ Example 5: Guess the Number Game (Difficulty ⭐⭐)
Output:
🎯 Guess the Number Game! Range 1-100
Please enter your guess:
⚠️ Please enter a valid number!
Too small! ⬆️
Too big! ⬇️
🎉 Congratulations, you got it right! The answer is 42
use std::io;
fn main() {
let secret = 42; // Hidden answer (random numbers will be used in subsequent lessons)
println!("🎯 Guess the Number Game! Range 1-100");
loop {
println!("Please enter your guess:");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read input");
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("⚠️ Please enter a valid number!");
continue;
}
};
match guess.cmp(&secret) {
std::cmp::Ordering::Less => println!("Too small! ⬆️"),
std::cmp::Ordering::Greater => println!("Too big! ⬇️"),
std::cmp::Ordering::Equal => {
println!("🎉 Congratulations, you got it right! The answer is {}", secret);
break;
}
}
}
}
Output:
🎯 Guess the Number Game! Range 1-100
Please enter your guess:
50
Too small! ⬆️
Please enter your guess:
75
Too big! ⬇️
Please enter your guess:
42
🎉 Congratulations, you got it right! The answer is 42
This example demonstrates the basic usage of
loop,match, the standard libraryio, and error handling—it is the classic introductory project from the official Rust tutorial.
6. A Quick Overview of the Rust Ecosystem
The Rust ecosystem revolves around three core tools:
| Tool | Purpose | Command |
|---|---|---|
| rustc | Rust compiler | rustc main.rs |
| rustup | Rust version management | rustup toolchain install nightly |
| Cargo | Package management + Build | cargo build / run / test / doc |
Open-source packages are hosted on crates.io (https://crates.io), which currently hosts over 150,000 packages. Common packages include serde (serialization), clap (command-line arguments), and tokio (asynchronous runtime).
❓ FAQ
cargo check and cargo build?cargo check only performs syntax and type checks; it does not generate binary files, so it is much faster.📖 Summary
- Rust is a systems-level programming language whose key selling points are compile-time memory safety and zero-cost abstraction.
- Compared to C/C++, Rust automatically manages memory; compared to Go, it has no GC pauses
- Use
rustupto install Rust; supports managing multiple versions Cargois Rust's package management and build system;cargo new/cargo build/cargo runare its three main features- Rust's ownership system is its most distinctive feature (which will be covered in depth in Lesson 8)
- The core of the ecosystem is on crates.io, where the community is active and continues to grow
📝 Exercises
- Difficulty ⭐: Use
cargo newto create a project namedmy_first_rust, modifymain.rsto print your name, and run it usingcargo run. - Difficulty ⭐⭐: Building on Example 3, add subtraction, multiplication, and division operations, and observe the results of different types of operations (Is integer division truncated?).
- Difficulty ⭐⭐⭐: Read the official Rust documentation opened by
rustup doc, find the "Ownership" section, and summarize it in three sentences in your own words. Send them to a Rust developer you know to see if they're correct.