Rust is a systems programming language known for its memory safety, zero-cost abstractions, and high performance. It prevents data races and memory errors at compile time through mechanisms such as ownership, borrowing, and lifetimes, while supporting efficient concurrent programming.

Memory Safety

One of Rust's core features is memory safety, which manages memory through an ownership system without a garbage collector. Ownership rules ensure that each value has a unique owner, and the value is automatically released when the owner goes out of scope. The example below demonstrates the basic concept of ownership.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership of s1 moves to s2
    // println!("{}", s1); // This line will cause a compilation error because s1 is no longer valid
    println!("{}", s2); // Output: hello
}

Tip: Rust's borrow checker enforces rules at compile time to prevent dangling pointers and data races.

Concurrent Programming

Rust makes concurrent programming safer through its ownership and type system. It uses threads and message passing to achieve concurrency, avoiding data races. The example below uses std::thread to create a thread.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("Hello from a thread!");
    });
    handle.join().unwrap();
}

Rust also provides tools like std::sync::Mutex and std::sync::Arc for safely sharing data.

Message Passing

Using channels for message passing is a common concurrency pattern in Rust. The example below shows how to use a std::sync::mpsc channel.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        tx.send("Hello from thread").unwrap();
    });
    println!("{}", rx.recv().unwrap()); // Output: Hello from thread
}

High Performance

Rust provides zero-cost abstractions, meaning that high-level features like iterators and closures have no runtime overhead. The example below uses iterators for efficient data processing.

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let doubled: Vec<_> = numbers.iter().map(|&x| x * 2).collect();
    println!("{:?}", doubled); // Output: [2, 4, 6, 8, 10]
}

Rust's compilation optimizations and low-level control allow it to match the performance of C/C++ while maintaining safety.