medium.com 6 min read Original Source

Why Rust Exists (And Why Most Languages Got It Wrong)

Not a Medium member yet? Read it here

Lesson 1: Introduction to Rust: The Future of Systems Programming

This is the first article in our journey to learn a new programming language in “comprehensive Rust series”. Whether you’re a seasoned systems programmer or completely new to Rust, this series will take me and you from fundamentals to expert level.

Honestly, I’ve been inclined towards Rust for quite some time but never found the time to enhance my skills. Now, I’m ready to take a small step on this learning experience, and I invite you to join me along the way.

After carefully consideration i decided to start with the history and the hype around Rust, so we can answer the fundamental existence of the language we will use in this whole series.

Before going any further: Lest clarify what This lesson in series Covers

This is a high level introduction to Rust. We won’t go deep into coding just yet . we’re laying the foundation. In upcoming lessons, we’ll break down these concepts with practical examples and hands on coding exercises.

Introduction

Programming languages have historically faced a trade off between performance and safety. Languages like Python and Java emphasised safety with garbage collection and runtime checks, while C and C++ deliver high performance at the cost of manual memory management. Considering i have worked in all of the mentioned languages, Rust provides a complete different solution to memory management and to my surprise is almost as efficient as C, almost. Rust was developed to offer both safety and performance simultaneously, addressing pitfalls of existing systems programming.

In this article, we explore:

  • The background and evolution of Rust
  • Core features such as ownership and memory safety
  • How Rust prevents common programming errors
  • Practical examples and code comparisons with C++
  • Its application in real-world systems and modern development environments

A Brief Background of Rust

Unsurprisingly, as many big ideas start in a garage or from personal passion, Rust also began as a personal project by Graydon Hoare at Mozilla Research in 2006. It was initially developed to address issues in system-level programming and was later adopted by Mozilla for the Servo project, a web browser engine designed for improved performance and safety.

Today, Rust is supported by major organisations including Microsoft, AWS, Google, and the Linux Foundation, and it is used in operating systems, web services, embedded systems, blockchain applications, and game engines. Since its official 1.0 release in 2015, Rust has continued to evolve and gain industry traction.

What is Rust?

Rust is a systems programming language developed for safety, concurrency, and high performance. It provided memory safety without compromising on the low level control and efficiency needed for systems development. In other words, working with c++ and C but as mentioned earlier, without worrying about the manual management of memory. Its key features are ad follow:

1. Memory Safety Without Garbage Collection

Unlike many high level languages that use garbage collection(Java familiar?) , Rust ensures memory safety at compile time through a system of ownership and borrowing. This method eliminates many issues in comparison with manual memory management, such as buffer overflows and use-after-free errors.

Consider the following comparison:

C++ Example — A Risky Approach:

//dangerous
int* getData() {
int data = 42;
return &data; // Returns pointer to local variable - dangerous!
}
//dangerous
int* getData() {
int data = 42;
return &data; // Returns pointer to local variable - dangerous!
}

This C++ code creates a “dangling pointer” by returning a reference to a local variable that will be destroyed when the function returns.

Rust Example — Preventing Dangling Pointers:

&i32 { // This code will not compile.
let data = 42;
&data
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn get_data() -> &i32 { // This code will not compile.
let data = 42;
&data
}
fn get_data() -> &i32 { // This code will not compile.
let data = 42;
&data
}

The Rust compiler prevents this error by recognising that the reference would outlive its data, thereby ensuring safety before the program is run.

2. Understanding Ownership: Rust’s Core Innovation

Ownership is the cornerstone of Rust’s approach to memory management. The rules are simple:

  1. Every value has exactly one owner.
  2. When the owner goes out of scope, the value is automatically dropped.
  3. You can have either one mutable reference or multiple immutable references, but not both simultaneously.

Example of Ownership in Rust:

fn main() {
let text = String::from("Hello"); // 'text' owns the string.
let borrowed = &text; // 'borrowed' is an immutable reference.
println!("{}", text); // Valid: accessing the original value.
println!("{}", borrowed); // Valid: accessing via reference.
let mut number = 42;
let ref1 = &mut number; // Borrowing 'number' mutably.
// let ref2 = &mut number; // This line would cause an error.
*ref1 = 43; // Modification through the mutable reference.
}
fn main() {
let text = String::from("Hello"); // 'text' owns the string.
let borrowed = &text; // 'borrowed' is an immutable reference.
println!("{}", text); // Valid: accessing the original value.
println!("{}", borrowed); // Valid: accessing via reference.
let mut number = 42;
let ref1 = &mut number; // Borrowing 'number' mutably.
// let ref2 = &mut number; // This line would cause an error.
*ref1 = 43; // Modification through the mutable reference.
}

3. Performance Comparable to C++

Rust provides low-level control similar to C and C++, but with the added benefits of safety checks at compile time. This design allows developers to write efficient code without incurring runtime overhead from garbage collection.

4. Lifetimes: Ensuring References are Valid

Lifetimes are a Rust feature that ensures references are always valid. They are annotations that tell the compiler how long a reference should live.

Example of Lifetimes:

<button data-code="fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let string1 = String::from("long string is long");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
fn main() {
    let string1 = String::from("long string is long");
    let string2 = "xyz";
    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
fn main() {
    let string1 = String::from("long string is long");
    let string2 = "xyz";
    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

Here, the lifetime 'a ensures that the returned reference is valid as long as both input references are valid.

We will talk about the syntax in the coming artcles , for now lest just see what is all the fuss about?

5. Error Handling: The Result and Option Types

Rust uses the Result and Option types for error handling, making it explicit and safe.

Example of Error Handling:

Result {
if b == 0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 0) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Division by zero"))
    } else {
        Ok(a / b)
    }
}
fn main() {
    match divide(10, 0) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Division by zero"))
    } else {
        Ok(a / b)
    }
}
fn main() {
    match divide(10, 0) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}

6. Concurrency Without Data Races

Concurrency is challenging because of the potential for race conditions when multiple threads access shared data simultaneously.

(Remember, the 500 million bug caused by the race condition )

Rust’s ownership system prevents such issues by ensuring that shared data is accessed safely.

Example — Concurrency Issue in Rust:

use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5];
// This will not compile: Rust prevents shared mutable state across threads.
thread::spawn(|| {
data.push(6); // Error: data may be accessed by multiple threads.
});
data.push(7);
}
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5];
// This will not compile: Rust prevents shared mutable state across threads.
thread::spawn(|| {
data.push(6); // Error: data may be accessed by multiple threads.
});
data.push(7);
}

For safe concurrent access, Rust requires explicit synchronisation:

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Final count: {}", *counter.lock().unwrap());
}
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Final count: {}", *counter.lock().unwrap());
}

7. Modern Development Tools

Rust includes a robust package manager called Cargo, which simplifies project management in a manner similar to npm for JavaScript or pip for Python. Cargo handles dependency management, building, and testing. For example:

Dependency Management (Cargo.toml):

[dependencies]
serde = "1.0"
tokio = { version = "1.0", features = ["full"] }
Building and Running a Project:
cargo build # Compile the project.
cargo run # Execute the project.
cargo test # Run tests.
[dependencies]
serde = "1.0"
tokio = { version = "1.0", features = ["full"] }
Building and Running a Project:
cargo build # Compile the project.
cargo run # Execute the project.
cargo test # Run tests.

Real World Applications

Rust’s balance of safety and performance makes it suitable for various applications:

  • Systems Programming:_ Mozilla utilised Rust for parts of Firefox, particularly in the CSS engine, to improve performance and reduce vulnerabilities._
  • Web Services:_ Companies like Discord have transitioned some services from Go to Rust, benefiting from its strong typing and efficient memory management._
  • Embedded Systems:_ Rust’s zero-cost abstractions and predictable resource cleanup are advantageous for embedded systems where resources are constrained._

Learning Curve and Considerations

While Rust introduces some new concepts (like ownership and lifetimes), these features help you write robust and error-free code. Here are a few tips to ease your journey:

  • The Rust Book: The official guide to learning Rust .
  • Rust by Example: A collection of runnable examples .
  • Practice:_ Start with small projects and gradually explore advanced topics like lifetimes and async programming._

But don’t feel overwhelmed , this series is intended to get you to a good start, hopefully.

Conclusion

Rust does a great work by showing us, that systems programming can achieve both safety and high performance. By addressing common drawbacks such as memory leaks, dangling pointers, and data races, developers write more efficient code using Rust. Although it introduces new paradigms, particularly in memory management , however , it offers benefits of reliability and maintainability.

As the language continues to evolve and gain adoption across various domains, its role in today’s software development is set to grow. Whether for operating systems, web services, or embedded systems, Rust represents a forward-thinking approach to building safe and efficient software.

Ready to start coding? In Lesson 2, we will:

  • Install Rust and Cargo
  • Set up a development environment
  • Write and run Our first Rust program?
  • Explore Rust syntax and data types

Follow this series and join us in mastering Rust from scratch!

Reach out here on Linkedin