Explicación de las referencias y el préstamo
Aprenda sobre referencias y préstamos, que permiten a varias partes del código acceder a los datos sin asumir su propiedad, de forma segura.
Explicación de las referencias y el préstamo es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 2 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 3 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What are References?
In Rust, variables own their data. But what if you need to let other parts of your code look at or even change that data without taking ownership?
That's where references come in! A reference is like a pointer to a value, but with strict rules enforced by the Rust compiler.
Think of it as looking at something through a window instead of owning the item itself.
Your First Reference
We create a reference using the & operator. This creates a non-owning pointer to a value. Let's see it in action:
fn print_length(s: &String) {
println!("The length is: {}", s.len());
}
fn main() {
let message = String::from("Hello, CoddyKit!");
print_length(&message); // Pass a reference
println!("Original message still here: {}", message);
}Understanding Borrowing
When you create a reference to a value, you are borrowing that value. The owner still owns it, but you get temporary access.
- Lending without giving away: You can use the borrowed data.
- No ownership transfer: The original variable still owns the data and will drop it when it goes out of scope.
- Safety first: Rust's borrowing rules prevent common programming errors like data races.
Immutable Borrows: Read-Only Access
By default, references in Rust are immutable. This means you can read the data they point to, but you cannot change it.
This is a core safety feature! If multiple parts of your code have read-only access, they can't accidentally interfere with each other's data.
Immutable Borrow in Practice
Here, the calculate_sum function takes an immutable reference to a vector. It can read the elements but cannot add or remove them.
fn calculate_sum(numbers: &Vec<i32>) -> i32 {
let mut total = 0;
for num in numbers {
total += num;
}
total
}
fn main() {
let my_numbers = vec![10, 20, 30, 40];
let sum = calculate_sum(&my_numbers); // Immutable borrow
println!("The sum is: {}", sum);
println!("Original vector: {:?}", my_numbers);
}Mutable Borrows: Changing Data
Sometimes, you need to modify data that you've borrowed. For this, you use a mutable reference, denoted by &mut.
Mutable references come with a crucial rule: you can only have one mutable reference to a particular piece of data at a time. This prevents data races and ensures safety.
Modifying Data with &mut
The add_suffix function takes a mutable reference to a String. It can modify the original String directly.
fn add_suffix(text: &mut String) {
text.push_str(" (modified)");
}
fn main() {
let mut my_string = String::from("Original text");
add_suffix(&mut my_string); // Mutable borrow
println!("Modified string: {}", my_string);
}The Golden Rules of Borrowing
Rust's compiler enforces these rules at compile time to guarantee memory safety:
- You can have one mutable reference to a piece of data at a time.
- OR, you can have any number of immutable references at a time.
- You cannot have a mutable reference while there are active immutable references.
- References must always be valid (they can't outlive the data they point to).
These rules prevent data races and ensure your programs are safe and predictable.
Conflicting Borrows
This code attempts to create both an immutable and a mutable reference to my_value at the same time, which violates Rust's borrowing rules. It will NOT compile.
Try to run it and see the compiler error!
fn main() {
let mut my_value = 100;
let r1 = &my_value; // Immutable reference
let r2 = &mut my_value; // Mutable reference (problem here!)
println!("r1: {}", r1);
// println!("r2: {}", r2); // This line would also cause an error if uncommented
}Check Your Understanding
Consider the following Rust code snippet:
fn process_data(data: &mut Vec<i32>) {
data.push(4);
}
fn main() {
let mut numbers = vec![1, 2, 3];
let first_ref = &numbers[0]; // Line A
process_data(&mut numbers); // Line B
println!("First element: {}", first_ref); // Line C
}Which line(s) will cause a compile-time error due to Rust's borrowing rules?
Recap: References & Borrowing
Great job! You've learned the fundamentals of references and borrowing in Rust:
- References (
&) allow you to access data without taking ownership. - Borrowing is the act of creating a reference, lending access to data.
- Immutable references (
&) provide read-only access. - Mutable references (
&mut) provide read/write access. - Rust's strict borrowing rules (one mutable OR many immutable) prevent data races and ensure memory safety at compile time.
These concepts are crucial for writing safe and efficient Rust code!
Preguntas frecuentes
¿La lección «Explicación de las referencias y el préstamo» es gratis?
Sí — el texto completo de «Explicación de las referencias y el préstamo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 3 lecciones en total.
¿Qué aprenderé en «Explicación de las referencias y el préstamo»?
Aprenda sobre referencias y préstamos, que permiten a varias partes del código acceder a los datos sin asumir su propiedad, de forma segura. Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Learn Rust Coding?
No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 3.
¿Cuánto tiempo toma la lección «Explicación de las referencias y el préstamo»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?
Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Comprensión del modelo de propiedad de Rust
- Explicación de las referencias y el préstamo
- Tiempos de vida para referencias seguras