Referências e Empréstimo Explicados
Aprenda sobre referências e empréstimo, permitindo que várias partes do seu código acedam aos dados sem assumirem a posse, de forma segura.
Referências e Empréstimo Explicados é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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!
Perguntas Frequentes
A aula “Referências e Empréstimo Explicados” é grátis?
Sim — o texto completo de “Referências e Empréstimo Explicados” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.
O que vou aprender em “Referências e Empréstimo Explicados”?
Aprenda sobre referências e empréstimo, permitindo que várias partes do seu código acedam aos dados sem assumirem a posse, de forma segura. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.
Quanto tempo leva a aula “Referências e Empréstimo Explicados”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Compreender o Modelo de Posse do Rust
- Referências e Empréstimo Explicados
- Tempos de Vida para Referências Seguras