Ownership e borrowing

Rust Smart Pointers: Box and Rc

Put data on the heap with Box and share one value between several owners with Rc.

  • Intermediário
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • Box<T> for recursive types
  • Rc<T> for shared ownership
  • Rc::strong_count
A list built with Box
  1. 1Node(1)points to
  2. 2Node(2)points to
  3. 3Node(3)points to
  4. 4Endsum = 6

Pointers that own their data

A smart pointer owns the data it points to. Box<T> stores a value on the heap, which makes recursive types possible. Rc<T> lets several owners share one value by counting them.

List contains itself, so its size would be infinite without Box: a Box has a fixed size because it is only a pointer. Rc::clone does not copy the string, it adds an owner, and strong_count shows three owners. The value is freed when the last owner is gone.

Pontos-chave

  1. Box has a fixed size, so a type can contain itself.
  2. Rc::clone adds an owner, it does not copy the data.
  3. The value is freed when the last owner is gone.

Exemplo executável de Rust

Rust
Executar código →
main.rs
use std::rc::Rc;

enum List {
    Node(i32, Box<List>),
    End,
}

fn sum(list: &List) -> i32 {
    match list {
        List::Node(value, next) => value + sum(next),
        List::End => 0,
    }
}

fn main() {
    let list = List::Node(1, Box::new(List::Node(2, Box::new(List::Node(3, Box::new(List::End))))));
    println!("sum = {}", sum(&list));

    let shared = Rc::new(String::from("shared config"));
    let reader_a = Rc::clone(&shared);
    let reader_b = Rc::clone(&shared);
    println!("{reader_a} / {reader_b}");
    println!("owners: {}", Rc::strong_count(&shared));
}
Gerar um botão Run para este exemplo Resultado da execução
sum = 6
shared config / shared config
owners: 3

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios