Skip to content

Q005. What does it mean for a value to own a resource?

Short Answer

A value owns a resource when its type gives it responsibility for that resource's lifecycle or for one owning handle to it. Dropping the value performs the type-defined cleanup, such as deallocating memory, closing a file descriptor, or releasing a lock. Ownership of a handle does not necessarily mean ownership of the external object behind it.

Deep Dive

Ownership represents cleanup responsibility:

  • String and Vec<T> own heap allocations;
  • File owns an OS file handle, not the file stored on disk;
  • TcpStream owns a socket handle, not the remote peer;
  • MutexGuard borrows a mutex but owns the responsibility to unlock it;
  • Arc<T> owns one counted share of an allocation.

Moving an owning value transfers its particular cleanup responsibility. Intentionally duplicating a handle is different: the API must define whether that creates a new owning handle, a shared ownership stake, or a non-owning view.

Internal Model

An owning value stores a type-specific representation such as an allocation pointer, file descriptor, platform handle, reference count handle, or pointer back to a lock. The OS or allocator does not know about a Rust move; the compiler changes which Rust place may perform cleanup.

When the owning value reaches its drop point, its Drop implementation and generated drop glue perform the required operation. A type with neither custom Drop logic nor fields requiring destruction may need no runtime cleanup.

Example

rust
use std::sync::Mutex;

fn increment(counter: &Mutex<u32>) {
    let mut guard = counter.lock().unwrap();
    *guard += 1;
} // guard is dropped and unlocks the mutex

fn main() {
    let counter = Mutex::new(0);
    increment(&counter);
}

Common Mistakes

  • Thinking only heap allocations can be owned resources.
  • Confusing ownership of a handle with ownership of the external system behind it.
  • Assuming every handle copy carries ownership and will run cleanup.

Follow-ups

  • How does an OS file descriptor differ from a Rust File value?
  • Why is MutexGuard an owning guard but not the owner of the mutex?
  • How can an API represent owning and borrowed handles?

References

  • The Rust Programming Language
  • Rust Standard Library
  • Linux man pages