💻 Programming

Borrow Checker

Borrow Checker

A core feature of the Rust compiler. Checks ownership and borrowing rules to guarantee memory safety.

📖 Detailed Explanation

The Borrow Checker is a core component of the Rust compiler that verifies ownership and borrowing rules at compile time. In this way, it guarantees memory safety and data race prevention without runtime overhead.

The key rules enforced by the Borrow Checker are as follows: at any given point, there can be only one mutable reference (&mut), or any number of immutable references (&). A mutable reference and an immutable reference cannot exist at the same time.

These rules prevent data races at compile time. When multiple threads access the same data, a data race can occur if at least one of them writes; Rust's type system blocks this at the source.

The Borrow Checker may feel restrictive at first, but once you get used to it, you end up writing safer and clearer code. With the introduction of NLL (Non-Lexical Lifetimes) in Rust, the Borrow Checker has become smarter, so more patterns are allowed than before.

💻 Code Example

Rust
fn main() {
    // 불변 빌림: 여러 개 가능
    let s = String::from("hello");
    let r1 = &s;
    let r2 = &s;
    println!("{}, {}", r1, r2);  // OK

    // 가변 빌림: 하나만 가능
    let mut s = String::from("hello");
    let r1 = &mut s;
    // let r2 = &mut s;  // 에러! 이미 가변 빌림 존재
    r1.push_str(" world");
    println!("{}", r1);

    // 불변 + 가변 동시 불가
    let mut s = String::from("hello");
    let r1 = &s;  // 불변 빌림
    // let r2 = &mut s;  // 에러! 불변 빌림이 아직 사용 중
    println!("{}", r1);  // r1 사용 종료

    // NLL: 사용 범위가 끝나면 새 빌림 가능
    let r2 = &mut s;  // OK! r1은 더 이상 사용되지 않음
    r2.push_str("!");
    println!("{}", r2);

    // 댕글링 참조 방지
    // fn dangle() -> &String {
    //     let s = String::from("hello");
    //     &s  // 에러! s는 함수 종료 시 해제됨
    // }

    // 올바른 방법: 소유권 이동
    fn no_dangle() -> String {
        let s = String::from("hello");
        s  // 소유권 이동
    }
}

🗣️ Examples of Practical Conversations

Junior Developer
"My code won't compile because of a Borrow Checker error. It feels too restrictive."
Senior developer
"It feels that way at first. But the errors the Borrow Checker catches are serious bugs that occur at runtime in other languages. Think of it as working with the compiler, not fighting it."
Junior Developer
"Could you show me some patterns?"
Interviewer
"What problem does Rust's Borrow Checker solve?"
Candidate
"It solves memory safety problems at compile time. It prevents bugs such as dangling pointers, double frees, and data races without runtime overhead."
Interviewer
"Why are RefCell and Mutex needed?"
Candidate
"They are used to defer borrowing rules to runtime. In cases where the compiler cannot prove safety, the interior mutability pattern performs borrow checking at runtime."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"You're using clone() a lot here. It looks like many of these cases could be solved with borrowing."
Author
"I used clone to avoid Borrow Checker errors. Could that cause performance issues?"
Reviewer
"Unnecessarily copying large data like String hurts performance. If you change the function signature to &str, borrowing solves it."

⚠️ Cautions

🔗 Related Terms

📚 Learn More