use std::cell::RefCell;
use std::collections::VecDeque;
struct TextEditor {
content: String,
history: RefCell<VecDeque<String>>,
}
impl TextEditor {
fn new(initial_content: &str) -> TextEditor {
TextEditor {
content: initial_content.to_string(),
history: RefCell::new(VecDeque::new()),
}
}
fn edit(&mut self, new_content: &str) {
self.history.borrow_mut().push_front(self.content.clone());
self.content = new_content.to_string();
}
fn undo(&mut self) -> Result<(), String> {
let mut history_borrow = self.history.borrow_mut();
if let Some(previous_content) = history_borrow.pop_front() {
self.content = previous_content;
self.history.borrow(); // panic
Ok(())
} else {
Err("No previous history available.".to_string())
}
}
fn print_content(&self) {
println!("Current content: {}", self.content);
}
}
fn main() {
let mut editor = TextEditor::new("Initial content");
editor.edit("First change");
editor.print_content();
editor.edit("Second change");
editor.print_content();
if editor.undo().is_ok() {
editor.print_content();
}
editor.history.borrow();
}
The following Rust code triggers panic, why is that?
After simplifying the logic a bit while coding and debugging it, I realized that it went panic because of borrowing issues, but why it didn’t do borrow checking at compile time but went panic?
Zx LLL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You’re using a RefCell, so you’re asking rust to borrow check at run time. If you want to borrow check at compile time, don’t use the RefCell.
RefCell
is a smart-pointers, that enforces borrow checker dynamically (at runtime) and Not in compile time.
you should read the docs
… However, there are situations where this rule (it’s talking about the compile time borrow checker) is not flexible enough. Sometimes it is required to have multiple references to an object and yet mutate it. Shareable mutable containers exist to permit mutability in a controlled manner, even in the presence of aliasing.
Cell<T>
,RefCell<T>
, andOnceCell<T>
allow doing this in a single-threaded way …
user26389150 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Rust’s compile-time borrow checker cannot handle dynamic borrowing patterns, such as those required for complex data structures that need to mutate their content through shared references. This is where RefCell comes in, enabling interior mutability and enforcing borrowing rules at runtime.
In your code, the panic is caused by trying to borrow history while it is already mutably borrowed.
You can use try_borrow()
instead to implicitly check for borrowing conflicts and handle the potential error gracefully:
match self.history.try_borrow() {
Ok(_borrow) => Ok(()),
Err(_) => Err("Failed to borrow history.".to_string()),
};
cardigan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.