0Pricing
Learn Rust Coding · Lección

Punteros inteligentes Box, Rc y Arc

Comprenda cómo `Box` para la asignación en el heap, `Rc` para la propiedad compartida y `Arc` para la propiedad compartida segura entre hilos gestionan los datos.

Punteros inteligentes Box, Rc y Arc es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 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 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.

Preguntas frecuentes

¿La lección «Punteros inteligentes Box, Rc y Arc» es gratis?

Sí — el texto completo de «Punteros inteligentes Box, Rc y Arc» 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 «Punteros inteligentes Box, Rc y Arc»?

Comprenda cómo `Box` para la asignación en el heap, `Rc` para la propiedad compartida y `Arc` para la propiedad compartida segura entre hilos gestionan los datos. 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 1 de 3.

¿Cuánto tiempo toma la lección «Punteros inteligentes Box, Rc y Arc»?

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

  1. Punteros inteligentes Box, Rc y Arc
  2. Mutabilidad interior: RefCell y Cell
  3. Concurrencia sin miedo con hilos
← Volver a Learn Rust Coding