Why can’t rust code process borrow checking at compile time?

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?

New contributor

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>, and OnceCell<T> allow doing this in a single-threaded way …

New contributor

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()),
};

New contributor

cardigan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật