0Pricing
Learn Rust Coding · Aula

Compreender o Modelo de Posse do Rust

Compreenda as regras fundamentais da posse e a semântica de movimento, bem como a forma como evitam erros comuns de memória, como a libertação dupla.

Compreender o Modelo de Posse do Rust é 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 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.

Perguntas Frequentes

A aula “Compreender o Modelo de Posse do Rust” é grátis?

Sim — o texto completo de “Compreender o Modelo de Posse do Rust” é 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 “Compreender o Modelo de Posse do Rust”?

Compreenda as regras fundamentais da posse e a semântica de movimento, bem como a forma como evitam erros comuns de memória, como a libertação dupla. 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 “Compreender o Modelo de Posse do Rust”?

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

  1. Compreender o Modelo de Posse do Rust
  2. Referências e Empréstimo Explicados
  3. Tempos de Vida para Referências Seguras
← Voltar para Learn Rust Coding