Ponteiros Inteligentes Box, Rc e Arc
Compreenda como `Box`, para alocação na memória heap, `Rc`, para posse partilhada, e `Arc`, para posse partilhada segura entre threads, gerem dados.
Ponteiros Inteligentes Box, Rc e Arc é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 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 Smart Pointers?
Rust's ownership system is great for memory safety, but sometimes you need more flexibility. That's where smart pointers come in!
Smart pointers are data structures that act like pointers but also have additional metadata and capabilities. They manage memory, ownership, and other resources automatically.
Box: Storing Data on the Heap
The simplest smart pointer is Box<T>. It allows you to store data on the heap instead of the stack.
- Stack: Fast, fixed-size data.
- Heap: Slower, flexible-size data, allocated at runtime.
When you put a value in a Box, the Box itself is on the stack, but the data it points to lives on the heap.
Using Box for Heap Allocation
Let's see how Box moves data to the heap. This is useful for large data or when you don't know the size at compile time.
Run this code to observe a value being boxed.
fn main() {
let x = 5; // x is on the stack
let boxed_x = Box::new(x); // x's value is moved to the heap, boxed_x is on stack
println!("Value on stack: {}", x);
println!("Value in Box (on heap): {}", *boxed_x); // Dereference to get value
}When Box is Useful
You might use Box<T> in these situations:
- When you have a type whose size can't be known at compile time, and you need to store it somewhere with a known, fixed size.
- When you have a large amount of data and want to transfer ownership without copying the data itself.
- When you want to own a trait object (e.g.,
Box<dyn Trait>).
Rc: Multiple Owners (Single Thread)
Rust's ownership rules mean a value usually has only one owner. But what if multiple parts of your program need to "own" the same data?
Rc<T>, or Reference Counted, allows multiple owners of data in a single-threaded scenario. It keeps track of how many references point to the data.
When the count drops to zero, the data is cleaned up.
Sharing Data with Rc
Rc::clone() increments the reference count. This isn't a deep copy; it just creates another pointer to the same data.
Notice how the data is shared, and its value is accessible from different "owners".
use std::rc::Rc;
fn main() {
let value = Rc::new(String::from("Shared String"));
println!("Count after creation: {}", Rc::strong_count(&value));
let value_clone_a = Rc::clone(&value); // Increment count
println!("Count after clone A: {}", Rc::strong_count(&value));
{
let value_clone_b = Rc::clone(&value); // Increment count
println!("Count after clone B: {}", Rc::strong_count(&value));
println!("Data from A: {}", value_clone_a);
println!("Data from B: {}", value_clone_b);
} // value_clone_b goes out of scope, count decreases
println!("Count after B goes out of scope: {}", Rc::strong_count(&value));
}Arc: Shared Ownership (Multi-Thread)
Rc<T> works well for single-threaded applications. However, if you need to share data between multiple threads, Rc<T> is not safe.
Arc<T>, or Atomic Reference Counted, is the thread-safe version of Rc<T>. It uses atomic operations to update the reference count, ensuring safety across threads.
Arc has a slight performance overhead compared to Rc due to atomic operations.
Sharing Data Across Threads with Arc
This example shows how Arc allows multiple threads to safely access and read the same shared data. Each thread gets its own `Arc` clone.
The main thread waits for all spawned threads to complete.
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(vec![1, 2, 3, 4, 5]);
let mut handles = vec![];
for i in 0..3 {
let data_clone = Arc::clone(&data); // Clone Arc for each thread
let handle = thread::spawn(move || {
println!("Thread {} has data: {:?}", i, *data_clone);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("All threads finished.");
}Box, Rc, or Arc?
Choosing the right smart pointer depends on your needs:
Box<T>: When you need to put data on the heap, typically for single ownership or when dealing with recursive types.Rc<T>: When you need multiple owners for data in a single-threaded context.Arc<T>: When you need multiple owners for data in a multi-threaded (concurrent) context.
Always prefer Box or Rc if you don't need thread safety, as Arc has a performance cost.
Smart Pointer Check
You need to store a large image file on the heap, and only one part of your program will own and manage it. Which smart pointer should you use?
Recap: Smart Pointers
In this lesson, you learned about three fundamental Rust smart pointers:
Box<T>: For allocating data on the heap with single ownership.Rc<T>: For enabling multiple owners of data in a single-threaded environment.Arc<T>: For enabling multiple, thread-safe owners of data in a multi-threaded environment.
These smart pointers give you more control over memory management while still leveraging Rust's safety guarantees.
Perguntas Frequentes
A aula “Ponteiros Inteligentes Box, Rc e Arc” é grátis?
Sim — o texto completo de “Ponteiros Inteligentes Box, Rc e Arc” é 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 “Ponteiros Inteligentes Box, Rc e Arc”?
Compreenda como `Box`, para alocação na memória heap, `Rc`, para posse partilhada, e `Arc`, para posse partilhada segura entre threads, gerem dados. 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 1 de 3.
Quanto tempo leva a aula “Ponteiros Inteligentes Box, Rc e Arc”?
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
- Ponteiros Inteligentes Box, Rc e Arc
- Mutabilidade Interior: RefCell e Cell
- Concorrência sem Receios com Threads