Borrow Checker
Borrow Checker
A core feature of the Rust compiler. Checks ownership and borrowing rules to guarantee memory safety.
Borrow Checker
A core feature of the Rust compiler. Checks ownership and borrowing rules to guarantee memory safety.
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.
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 // 소유권 이동
}
}
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free