WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 18 of 100

Explain the concept of ownership and borrowing in Rust.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

Ownership and borrowing are two key concepts in Rust’s memory management system that help ensure memory safety and prevent common programming errors such as null pointer dereferences, use-after-free errors, and data races.

Ownership in Rust refers to the idea that every piece of memory has a unique owner, which is responsible for managing its lifetime and determining when it is no longer needed. When an object is created in Rust, it is assigned an owner, which is usually the variable that was used to create it. The owner can then pass the object to other variables or functions, but it remains responsible for freeing the memory when it is no longer needed.

For example, consider the following code:

    let mut s = String::from("hello");
    let s2 = s;

In this code, we create a new String object ‘s‘ containing the value "hello". We then assign the value of ‘s‘ to a new variable ‘s2‘. However, unlike many other programming languages that would create a copy of the string data, in Rust the ownership of the string is "moved" to ‘s2‘, which means that ‘s‘ is no longer valid and attempting to use it will result in a compiler error. The string data is then freed automatically when ‘s2‘ goes out of scope.

Borrowing in Rust refers to the idea that multiple references to the same object can be created, allowing multiple parts of the code to access and modify the object simultaneously. However, only one reference can have mutable access to the object at a time, which prevents data races and ensures that the object’s state remains consistent.

For example, consider the following code:

    fn string_length(s: &String) -> usize {
        s.len()
    }
    
    fn main() {
        let s = String::from("hello");
        let len = string_length(&s);
        println!("The length of '{}' is {}.", s, len);
    }

In this code, we pass a reference to the ‘String‘ object ‘s‘ to the ‘string_length‘ function using the ‘&‘ symbol to create an immutable reference. This allows us to access the length of the string without transferring ownership of the object. The ‘&String‘ type is a borrowed reference, because the function only borrows the object for the duration of the function call and does not take ownership of it. When the function returns, the reference goes out of scope and the object remains owned by the variable ‘s‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics