
Ownership & Borrowing
Ownership rules, move semantics, borrowing (&T, &mut T), lifetimes, dangling references
1What is ownership in Rust?
What is ownership in Rust?
回答
Ownership is a fundamental system in Rust that guarantees memory safety without a garbage collector. Each value has a single owner, and memory is automatically freed when the owner goes out of scope. This system prevents data races and use-after-free errors at compile time.
2How many owners can a value have in Rust?
How many owners can a value have in Rust?
回答
In Rust, a value can only have one owner at a time. This is the first rule of ownership. When ownership is transferred (move), the previous owner can no longer access the value. This rule ensures that no two parts of the code can modify or free the same memory.
3What happens when a variable goes out of scope in Rust?
What happens when a variable goes out of scope in Rust?
回答
When a variable goes out of scope, Rust automatically calls the drop function which frees the memory. This behavior is deterministic and predictable, unlike garbage collectors that free memory non-deterministically. This pattern is called RAII (Resource Acquisition Is Initialization).
What is a move in Rust?
Which types implement the Copy trait in Rust?
+19 面接問題