0Pricing
Learn Rust Coding · Lección

Comprensión del modelo de propiedad de Rust

Comprenda las reglas fundamentales de la propiedad, la semántica de movimiento y cómo evitan errores habituales de memoria, como la liberación doble.

Comprensión del modelo de propiedad de Rust 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 is Rust Ownership?

Rust's ownership system is a set of rules that manage how your program uses memory. It's a core concept that helps Rust achieve memory safety without a garbage collector.

  • No dangling pointers.
  • No double-free errors.
  • No data races in concurrent code.

It checks these rules at compile time!

Stack vs. Heap Memory

Programs use two main memory areas: the stack and the heap.

  • Stack: Faster, fixed-size data (like integers, booleans, known-size types). Data is pushed and popped in order.
  • Heap: Slower, variable-size data (like String, Vec). Data is requested and returned by the allocator.

Ownership primarily manages data on the heap, ensuring its safe use and cleanup.

Rule 1: Every Value Has an Owner

The first rule of ownership is simple: each value in Rust has a variable that's called its owner.

Think of it like a label on a box. The variable s below is the owner of the text "hello".

fn main() {
  let s = String::from("hello"); // s owns "hello"
  println!("{}", s);
}

Rule 2: Only One Owner at a Time

The second rule states: at any given time, there can only be one owner for a value. This is crucial for preventing memory issues.

When you assign a complex value (like a String, which lives on the heap) from one variable to another, ownership is moved, not copied.

Ownership Transfer in Action

See what happens when s1's value is assigned to s2. Try running the code.

fn main() {
  let s1 = String::from("Hello, CoddyKit!");
  let s2 = s1; // Ownership of the String data moves from s1 to s2

  // println!("{}", s1); // This line would cause a compile-time error!
  println!("{}", s2);
}

Understanding "Move" Semantics

After let s2 = s1;, s1 is no longer considered valid. Rust prevents you from using s1 again.

  • This is called a move. The pointer, length, and capacity on the stack are copied, but the heap data itself is not.
  • If s1 were still valid, both s1 and s2 would try to free the same memory when they go out of scope (a double-free error).

Rust's ownership system prevents this at compile time!

Ownership and Function Calls

Passing a value to a function works similarly to assigning it to another variable: ownership is moved into the function.

When the function finishes, the value's owner (the function parameter) goes out of scope, and the value is dropped.

Function Ownership Demo

Observe how the String value is moved into takes_ownership and then gives_ownership returns a new String.

fn takes_ownership(some_string: String) {
  println!("Inside takes_ownership: {}", some_string);
} // some_string goes out of scope and `drop` is called.

fn gives_ownership() -> String {
  let some_string = String::from("returned string");
  some_string // Ownership is moved out of the function
}

fn main() {
  let s1 = String::from("hello");
  takes_ownership(s1); // s1's value moves into takes_ownership
  // println!("{}", s1); // Error: s1 is no longer valid here!

  let s2 = gives_ownership(); // s2 gets ownership of the returned String
  println!("After gives_ownership: {}", s2);
}

Rule 3: Scope & Dropping

The final rule: when the owner goes out of scope, the value will be dropped.

  • A scope is the range within a program for which an item is valid, usually defined by {} curly brackets.
  • When a variable goes out of scope, Rust automatically calls a special function called drop.

This ensures memory is cleaned up automatically, safely, and without a garbage collector.

Preventing Memory Errors

The ownership rules work together to guarantee memory safety:

  • One owner: Prevents multiple parts of your code from trying to free the same memory.
  • Drop on scope end: Ensures memory is freed exactly once, and at the correct time.

This eliminates common bugs like double-free errors and use-after-free errors at compile time, giving you peace of mind!

Ownership Check

Consider the following Rust code. What will happen when you try to compile and run it?

fn main() {
  let message = String::from("Rust is fun!");
  let greeting = message;
  println!("{}", message);
}

Recap: Ownership Basics

Great job! You've learned the fundamental rules of Rust's ownership system:

  • Every value has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value is dropped.

This system prevents common memory errors without a garbage collector. Next, we'll explore borrowing to share data without transferring ownership.

Preguntas frecuentes

¿La lección «Comprensión del modelo de propiedad de Rust» es gratis?

Sí — el texto completo de «Comprensión del modelo de propiedad de Rust» 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 «Comprensión del modelo de propiedad de Rust»?

Comprenda las reglas fundamentales de la propiedad, la semántica de movimiento y cómo evitan errores habituales de memoria, como la liberación doble. 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 «Comprensión del modelo de propiedad de Rust»?

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. Comprensión del modelo de propiedad de Rust
  2. Explicación de las referencias y el préstamo
  3. Tiempos de vida para referencias seguras
← Volver a Learn Rust Coding