Skip to content
rustintermediate

Rust Ownership In Depth

Lifetimes, smart pointers and borrowing rules

7 questions

By EZ4Code Team

1. What is the main purpose of lifetime annotations?

To tell the compiler about the relationships between references' lifetimes to avoid dangling references
To change runtime behavior
To improve performance
To declare variable scopes
Explanation: Lifetime annotations (such as 'a) describe relationships between references, helping the borrow checker verify reference validity and eliminating dangling references at compile time.

2. What is the purpose of Box<T>?

To allocate data on the heap with unique ownership
To share ownership
To provide interior mutability
For thread synchronization
Explanation: Box<T> is a heap-allocating smart pointer with exclusive ownership, used to place data on the heap or to build recursive types (such as linked lists).

3. What is the difference between Rc<T> and Arc<T>?

Rc is single-threaded reference counting; Arc is atomic reference counting and thread-safe
They are exactly the same
Arc is not thread-safe
Rc is used for multithreading
Explanation: Rc<T> uses non-atomic reference counting and is single-threaded only; Arc<T> (Atomic Rc) uses atomic operations and can share ownership across threads.

4. What feature does RefCell<T> provide?

Interior mutability: checks borrowing rules at runtime under an immutable borrow
Compile-time borrow checking
Thread safety
Heap allocation
Explanation: RefCell<T> provides interior mutability by moving borrow checking to runtime (panicking on violation), commonly used to mutate immutable data in single-threaded scenarios.

5. What happens with dangling references in Rust?

Forbidden at compile time
Panics at runtime
Allowed to exist
Need to be manually freed
Explanation: The Rust borrow checker ensures at compile time that references never outlive the data they refer to, eliminating dangling references at the source.

6. What does the 'static lifetime mean?

The reference is valid for the entire duration of the program
It only lives for an instant
It can only be used in the main function
It represents a local variable
Explanation: 'static means the reference is valid for the entire lifetime of the program, such as string literals &'static str.

7. What is the purpose of the Drop trait?

To define cleanup logic (destructor) when a value goes out of scope
To copy a value
To compare equality
To print output
Explanation: Types that implement the Drop trait automatically call the drop method when leaving scope, used to release resources (such as files, locks) without manual free.

More rust Quizzes