💻 Programming

Ownership

Ownership

Rust's core memory management concept. Each value has exactly one owner and is automatically freed when it goes out of scope. Guarantees memory safety without a GC.

📖 Detailed Explanation

Ownership is the most central and distinctive concept of the Rust programming language. It verifies memory management at compile time and guarantees memory safety without runtime overhead. It is an innovative approach that simultaneously solves the bugs caused by manual memory management in C/C++ (dangling pointer, double free, use-after-free) and the performance problems of GC languages.

The Three Rules of Ownership

  1. Each value has a single owner - Every value in Rust can have only one variable (the owner).
  2. Scope determines lifetime - When the owner goes out of scope, the value is automatically dropped (freed).
  3. Move semantics by default - When a value is assigned to another variable, ownership is moved, and the original variable can no longer be used.

Borrowing and References are concepts that complement Ownership. You can temporarily borrow a value without transferring ownership. Multiple immutable references (&T) can exist at the same time, but only one mutable reference (&mut T) is allowed at a time. This rule prevents data races at compile time.

The greatest advantage of the Ownership system is that it guarantees memory safety without a Garbage Collector. Without a GC, it offers predictable performance and low memory overhead, and it is gaining attention in performance-critical fields such as systems programming, embedded, and game engines. Because the borrow checker verifies every memory access at compile time, runtime crashes do not occur.

💻 Code Example

// === Ownership 기본 예제 ===

fn main() {
    // 1. 기본 Ownership: String은 힙에 할당됨
    let s1 = String::from("hello");
    let s2 = s1;  // s1의 소유권이 s2로 이동(move)
    // println!("{}", s1);  // 컴파일 에러! s1은 더 이상 유효하지 않음
    println!("{}", s2);  // OK: "hello"

    // 2. Clone: 깊은 복사로 소유권 유지
    let s3 = String::from("world");
    let s4 = s3.clone();  // 힙 데이터까지 복사
    println!("s3: {}, s4: {}", s3, s4);  // 둘 다 유효

    // 3. Copy trait: 스택 데이터는 자동 복사
    let x = 5;
    let y = x;  // i32는 Copy trait 구현, x도 여전히 유효
    println!("x: {}, y: {}", x, y);  // 둘 다 유효

    // 4. 함수와 Ownership
    let s5 = String::from("rust");
    takes_ownership(s5);  // s5의 소유권이 함수로 이동
    // println!("{}", s5);  // 컴파일 에러!

    let s6 = gives_ownership();  // 함수로부터 소유권 받음
    println!("받은 값: {}", s6);
}

fn takes_ownership(s: String) {
    println!("소유권 받음: {}", s);
}  // s가 drop됨

fn gives_ownership() -> String {
    String::from("새로운 문자열")  // 소유권 반환
}

// === Borrowing과 References ===

fn borrowing_example() {
    let s1 = String::from("hello");

    // 불변 참조 (Immutable borrow)
    let len = calculate_length(&s1);  // 빌려주기만 함
    println!("'{}' 길이: {}", s1, len);  // s1 여전히 유효

    // 가변 참조 (Mutable borrow)
    let mut s2 = String::from("hello");
    change(&mut s2);
    println!("변경됨: {}", s2);  // "hello, world"

    // 참조 규칙: 불변 참조 여러 개 OK
    let r1 = &s1;
    let r2 = &s1;
    println!("{} {}", r1, r2);

    // 가변 참조는 단 하나만!
    let mut s3 = String::from("test");
    let r3 = &mut s3;
    // let r4 = &mut s3;  // 컴파일 에러! 동시에 두 개의 가변 참조 불가
    println!("{}", r3);
}

fn calculate_length(s: &String) -> usize {
    s.len()  // 참조로 받았으므로 소유권 이동 없음
}

fn change(s: &mut String) {
    s.push_str(", world");  // 가변 참조로 수정 가능
}

🗣️ Examples of Practical Conversations

In a Rust Developer Technical Interview

"Ownership is the core mechanism by which Rust guarantees memory safety without a GC. Each value has only one owner, and when the owner goes out of scope, it is automatically dropped. Through Borrowing, you can reference a value without transferring ownership; multiple immutable references are possible, but only one mutable reference is allowed at a time. This rule prevents data races at compile time."

In a GC vs Ownership Technical Debate

"GC offers high development convenience, but it is unsuitable for real-time systems because of Stop-the-world issues. Rust's Ownership tracks memory at compile time, so there is no runtime overhead. Of course, the initial learning curve is steep because you have to fight the borrow checker, but you can get C++-level performance without memory bugs, so it is ideal for systems programming. Our team rewrote a performance-critical microservice in Rust and reduced memory usage by 60%."

During a Team Code Review

"I see you used clone() when passing the String to the function, but if it's only being read, please lend it as a &str reference. It reduces unnecessary heap allocations. Also, when you return the Vec in this loop, ownership moves, so you'll get an error in the next iteration. Using into_iter() instead of iter(), or handling it by reference, is the right approach."

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

⚠️ Cautions

1
Move vs Copy

Types stored on the stack, such as integers, floating-point numbers, bool, and char, implement the Copy trait and are copied automatically. However, types that hold heap data, such as String, Vec, and Box, are Moved. Confusing whether a type is Copy can cause unexpected compile errors.

2
Understanding Lifetime Is Essential

A Lifetime annotation ('a) is required when returning a reference or storing it in a struct. A Lifetime specifies the scope in which a reference is valid, preventing dangling references. It may look complicated at first, but you will gradually come to understand it by following the compiler messages.

3
How to Deal with Borrow Checker Errors

When a borrow checker error occurs, don't panic and read the error message carefully. In most cases, it can be resolved by copying the ownership with clone(), adjusting the reference scope, or switching to runtime borrow checking with RefCell/Rc. Rather than relying on clone() unconditionally, it is better to reexamine the design.

🔗 Related Terms

📚 Learn More