ExpertiDict

Rust · Intermediário · Inglês · Técnico

RefCell

/ˈrɛf sɛl/substantivo

Contêiner que move a checagem de empréstimos para a execução. Permite alterar um valor mesmo por referência compartilhada, e causa panic se as regras forem violadas.

Onde usar

Costuma vir como Rc<RefCell<T>> para estruturas compartilhadas e mutáveis em uma só thread. O panic 'already borrowed' indica dois empréstimos incompatíveis.

Em código

use std::cell::RefCell;
let c = RefCell::new(vec![1]);
c.borrow_mut().push(2);
println!("{:?}", c.borrow());

Exemplos

It panicked with already borrowed on the RefCell.

Deu panic de already borrowed no RefCell.

Wrap it in a RefCell to mutate through Rc.

Envolva em um RefCell para mutar através do Rc.

Cuidado

RefCell não desliga o borrow checker: as regras continuam valendo, só que conferidas em tempo de execução.

Veja também

Todos os termos de Rust