Ever wondered what lies behind Rust libraries? In this article, I invite you to explore Rust’s source code in a simple and practical way. It doesn’t matter if you’re just getting started or already have some experience: here you’ll learn to read code like a pro, step by step, with clear examples, useful tools, and real-world projects. Let’s dive into the world of Rust together!
Table of Contents (Levels: Beginner | Intermediate | Advanced):
- Rust Basics (Beginner)
- Tools for Exploring Code (Beginner)
- Reading Simple Modules (Beginner)
- Memory Management for Mere Mortals (Intermediate)
- Smart Pointers in Detail (Intermediate)
- Traits and Trait Objects (Advanced)
- Real Projects to Analyze (Advanced)
1. Rust Basics (Beginner)
Before jumping into the code, let’s review the essentials with examples anyone can understand.
Ownership and Borrowing
Rust has unique rules for managing memory, centered around the concept of ownership. Look at this example:
fn main() {
let s1 = String::from("hola"); // s1 es el dueño de "hola"
let s2 = s1; // s1 "cede" la propiedad a s2
// println!("{}", s1); // ¡Error! s1 ya no existe aquí
}
This is what Rust calls move semantics: when you assign s1 to s2, the value is “moved” and s1 is no longer valid.
Option and Result
Rust doesn’t use exceptions like other languages. Instead, it uses Option (for values that might not exist) and Result (for operations that might fail). For example:
fn dividir(a: f64, b: f64) -> Result {
if b == 0.0 {
Err("No se puede dividir por cero".to_string())
} else {
Ok(a / b)
}
}
Try it yourself: Change the value of b to 0.0 and see what happens when you run it.
2. Tools for Exploring Code (Beginner)
Reading code is much easier with the right tools. Here are two you will love:
A. rust-analyzer in VSCode
- Install the “rust-analyzer” extension in VSCode.
- Right-click on something like
Stringand select Go to Definition. - Boom! You’re looking at the source code of
Stringright inside the standard library.
B. cargo doc –open
Want to inspect documentation for your own project? In your terminal, run:
cargo doc --open
3. Reading Simple Modules (Intermediate)
Let’s start with something simple: how does a Vec work (the Rust equivalent of a dynamic array or list)?
std::vec::Vec: How does it grow?
Here is how you create a vector:
let mut v = Vec::new(); // Empieza vacío, capacidad = 0
v.push(1); // Ahora tiene capacidad para 4 elementos
v.push(2); // Capacidad = 4, pero solo 2 elementos usados
This is what it looks like in memory:
+---------+----------+---------+
| Puntero | Capacidad| Longitud|
+---------+----------+---------+
| 4 2
v
Heap: [1, 2, _, _] // "_" = espacio reservado pero vacío
Try it yourself: Run cargo expand in a project containing vec![1, 2] to discover how that macro expands under the hood.
4. Memory Management for Mere Mortals (Intermediate)
Ownership might sound intimidating, but it is simpler than it seems. Think of a String as a library book:
- Only one person can take it home (ownership).
- You can lend it to others to read (
&T) or edit (&mut T), but under strict rules.
Take a look at this example:
fn prestar_libro(libro: &String) {
println!("Leyendo: {}", libro);
}
fn main() {
let mi_libro = String::from("El Señor de los Anillos");
prestar_libro(&mi_libro); // Lo presto para leer
prestar_libro(&mi_libro); // ¡Puedo prestarlo otra vez!
}
Here, &mi_libro is an immutable borrow: multiple readers can view it, but nobody can modify it.
5. Smart Pointers in Detail (Advanced)
Smart pointers are advanced tools for managing memory. Let’s look at the most common ones:
Box<T>
Allocates data on the heap (dynamic memory):
let b = Box::new(5);
println!("b = {}", b); // b = 5
Rc<T>
Allows multiple “owners” to share a value:
use std::rc::Rc;
let a = Rc::new(10);
let b = Rc::clone(&a);
println!("Dueños: {}", Rc::strong_count(&a)); // 2}
RefCell<T>
Enables interior mutability, letting you modify data at runtime while enforcing borrow rules dynamically:
use std::cell::RefCell;
let data = RefCell::new(5);
*data.borrow_mut() += 1;
println!("Dato: {}", data.borrow()); // Dato: 6
Try it yourself: Build a structure combining Rc and RefCell to share a mutable value across multiple locations.
6. Traits and Trait Objects (Advanced)
Traits define shared behavior, like an interface or contract. Imagine you want different shapes to be “drawable”:
trait Dibujable {
fn dibujar(&self);
}
struct Circulo {
radio: f64,
}
impl Dibujable for Circulo {
fn dibujar(&self) {
println!("Círculo de radio {}", self.radio);
}
}
struct Rectangulo {
ancho: f64,
alto: f64,
}
impl Dibujable for Rectangulo {
fn dibujar(&self) {
println!("Rectángulo de {}x{}", self.ancho, self.alto);
}
}
fn dibujar_forma(forma: &dyn Dibujable) {
forma.dibujar();
}
fn main() {
let circulo = Circulo { radio: 5.0 };
let rectangulo = Rectangulo { ancho: 3.0, alto: 4.0 };
dibujar_forma(&circulo);
dibujar_forma(&rectangulo);
}
Try it yourself: Add a Triangulo struct with its own fields and implement Dibujable for it.
7. Real Projects to Analyze (Advanced)
A. The regex crate
- Visit docs.rs/regex.
- Click on “Source” and search for the
findfunction. - Trace the code to see how it matches patterns.
Question: What does regex do if you provide an invalid pattern?
B. Your First Contribution
- Find a repository like serde labeled with “good first issue”.
- Read the contributing guidelines.
- Try improving documentation or adding a test case, then submit a pull request.
C. Build a Generic Stack
Here is a foundation for a stack using Vec:
struct Stack {
elementos: Vec,
}
impl Stack {
fn new() -> Self {
Stack { elementos: Vec::new() }
}
fn push(&mut self, elemento: T) {
self.elementos.push(elemento);
}
fn pop(&mut self) -> Option {
self.elementos.pop()
}
fn is_empty(&self) -> bool {
self.elementos.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(elemento) = stack.pop() {
println!("Elemento: {}", elemento);
}
}
Try it yourself: Add a peek method that inspects the top element without popping it.
8. Resources to Keep Learning
Books and Tutorials
- The Rust Programming Language Book: Read about ownership (Chapter 4) and generics (Chapter 10).
- Rust by Example: Hands-on exercises.
Communities
- Rust Users Forum: Ask anything.
- Rust en Español: Join the Spanish Telegram group.
Practice Makes Perfect
Reading Rust code is like reading a map: it might seem confusing at first, but with practice, the paths become clear. Use the tools and examples in this guide to explore at your own pace. Don’t worry if you don’t understand everything on the first pass; tweak examples, tinker with code, and share your discoveries with others.
Next steps:
- Clone a small project like ripgrep.
- Run
cargo doc --opento explore its internal modules. - Publish your own crate and share it with the world!
Mini Glossary:
- Trait: A contract of methods and behavior that a type can implement.
- Macro: Code that writes more code for you at compile time.
- Crate: A Rust compilation unit, package, or library.
Hopefully, this guide gives you everything you need to start exploring Rust without getting frustrated. Happy hacking, and let’s keep coding!
Appendix: Exercise Solutions
Vec Exercise: With cargo expand, vec![1, 2] expands roughly to:
let mut v = Vec::new();
v.push(1);
v.push(2);
Regex Exercise: If the pattern fails compilation, Regex::new returns an Err variant inside a Result.
Stack Solution with peek:
impl Stack {
fn peek(&self) -> Option<&T> {
self.elementos.last()
}
}