A C++ veteran, eh? Welcome to Rust! You'll feel right at home with its systems programming focus, performance, and lack of garbage collection. Rust is designed to give you memory safety guarantees without sacrificing control or speed. Let's dive into the language features, with examples, highlighting the similarities and differences with C++.
What is Rust?
Rust is a statically typed, compiled, general-purpose programming language focused on:
- Memory Safety: No null pointer dereferences, dangling pointers, or data races.
- Performance: Comparable to C++ (often identical).
- Concurrency: Built-in support for concurrent programming.
Rust achieves these goals through its unique ownership system and borrow checker. Don't worry; it's easier than it sounds!
Basic Syntax
Rust's syntax is similar to C++'s, with some tweaks. Here's a "Hello, World!" to get you started:
fn main() {
println!("Hello, World!"); // println! is a macro (more on this later)
}
fn declares a function (like void in C++).
main is the entry point.
println! prints to the console with a newline (the ! denotes a macro).
Variables and Mutability
In Rust, variables are immutable by default. This is a deliberate design choice to prevent unintended changes.
let x = 5; // immutable variable (like `const int x = 5;` in C++)
// x = 10; // Error! Cannot assign twice to immutable variable
let mut y = 5; // mutable variable (like `int y = 5;` in C++)
y = 10; // Okay!
let declares a variable.
mut keyword makes the variable mutable.
Data Types
Rust has the usual primitive types:
- Integers:
i32 (signed 32-bit), u32 (unsigned 32-bit), isize (pointer-sized signed integer), etc.
- Floats:
f32, f64
- Boolean:
bool
- Character:
char ( Unicode scalar value, 4 bytes)
Here's an example:
let a: i32 = 10; // explicit type annotation (rarely needed, Rust infers types)
let b = 20u8; // unsigned 8-bit integer, type inferred
let c = 3.14f64; // 64-bit float, type inferred
Ownership System
This is where Rust diverges from C++. Ownership rules govern how Rust manages memory:
- Each value has an owner (the scope where it's defined).
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (memory freed).
Example:
{
let s = String::from("hello"); // `s` owns the string
// use `s` here...
} // `s` goes out of scope, string memory is freed automatically
No delete needed! Rust inserts the equivalent of delete at the end of the scope.
Moves
When you assign a value to another variable, the ownership is moved:
let s1 = String::from("hello");
let s2 = s1; // `s1`'s ownership is moved to `s2`
// `s1` is no longer valid here!
// println!("{}", s1); // Error! Use of moved value
This prevents double-free errors. If you want a copy, use clone():
let s1 = String::from("hello");
let s2 = s1.clone(); // `s1` remains valid, `s2` is a copy
println!("{}", s1); // Okay!
References (Borrows)
To use a value without taking ownership, use references (&):
let s = String::from("hello");
let len = calculate_length(&s); // `s` is borrowed, not moved
println!("{}", s); // Still valid!
fn calculate_length(s: &String) -> usize {
s.len()
}
&s creates a reference to s (like a pointer, but safer).
s: &String means s is a reference to a String.
Mutable References
To modify a borrowed value, use &mut:
let mut s = String::from("hello");
change_string(&mut s); // `s` is mutably borrowed
fn change_string(s: &mut String) {
s.push_str(", world!");
}
Rules of Borrows:
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid (no dangling pointers).
The borrow checker enforces these rules at compile-time. If your code passes, you have memory safety guarantees.
Structs and Enums
Similar to C++ struct and enum, with some extra powers:
struct Person {
name: String,
age: u8,
}
enum Color {
Red,
Green,
Blue(u8), // With associated value
}
let person = Person {
name: String::from("John"),
age: 30,
};
let color = Color::Blue(255);
Pattern matching with match (like switch in C++, but more powerful):
match color {
Color::Red => println!("Red"),
Color::Green => println!("Green"),
Color::Blue(brightness) => println!("Blue with brightness {}", brightness),
}
Methods and Impls
Attach methods to structs using impl:
impl Person {
fn greet(&self) { // `&self` is like `this` in C++
println!("Hi, my name is {}!", self.name);
}
}
person.greet(); // Hi, my name is John!
Error Handling
Rust uses Result and Option enums for error handling:
enum Result<T, E> {
Ok(T),
Err(E),
}
enum Option<T> {
Some(T),
None,
}
Example:
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
match f {
Ok(file) => println!("File opened: {:?}", file),
Err(err) => println!("Error opening file: {}", err),
}
}
Or, use unwrap/expect for simpler cases (panic if error):
let f = File::open("hello.txt").expect("Failed to open file");
Macros
Rust's macro system is hygienic (no name clashes) and compile-time evaluated. You've seen println! already:
macro_rules! say_hello {
() => {
println!("Hello!");
};
}
fn main() {
say_hello!(); // Expands to println!("Hello!") at compile-time
}
Concurrency
Rust's ownership system helps prevent data races. Use threads with std::thread:
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from another thread!");
});
handle.join().unwrap(); // Wait for the thread to finish
}
Send data between threads using channels (std::sync::mpsc) or mutexes (std::sync::Mutex).
Zero-Cost Abstractions
Like C++, Rust has zero-cost abstractions: abstractions that compile to the same machine code as handwritten, optimized code. Examples include:
- Iterators
- Smart pointers (
Box, Rc, Arc)
let numbers = vec![1, 2, 3, 4, 5];
let sum = numbers.into_iter().sum::<i32>(); // Zero-cost abstraction
Where to Go Next
- The Rust Book (official documentation): https://doc.rust-lang.org/book/
- Rust by Example: https://doc.rust-lang.org/rust-by-example/
- Rustlings (small exercises): https://github.com/rust-lang/rustlings/
- Playground (online Rust environment): https://play.rust-lang.org/
Coming from C++, you'll appreciate Rust's:
- Similar performance
- Memory safety guarantees
- Modern language features
- Growing ecosystem
You'll miss:
- Unrestricted pointer arithmetic (it's mostly unnecessary in Rust)
- Multiple mutable references (borrow checker will stop you)
Give Rust a try! It's a systems programming language for the 21st century. Happy coding!