Câu hỏi phỏng vấn Rust
Câu hỏi

What happens when you pass a String to a function in Rust?

Câu trả lời

When you pass a String to a function in Rust, the ownership of that String is transferred to the function. This means that the original variable that held the String will no longer be valid after the function call, and attempting to use it will result in a compile-time error. This behavior is due to Rust's ownership model, which ensures memory safety by enforcing strict rules about how data is accessed and modified.

Here is a detailed explanation of what happens:

  1. Ownership Transfer: When a String is passed to a function, the ownership of the String is moved to the function parameter. The original variable that held the String is no longer valid after the function call.

    rust Copy
    fn takes_ownership(some_string: String) {
        println!("{}", some_string);
    }
    
    fn main() {
        let s = String::from("hello");
        takes_ownership(s);
        // println!("{}", s); // This line would cause a compile-time error because `s` is no longer valid.
    }
  2. Move Semantics: The move semantics in Rust mean that the function now owns the String and is responsible for its cleanup. When the function scope ends, the String will be dropped, and its memory will be freed.

  3. Compile-Time Safety: Rust's compiler enforces these rules at compile time, preventing issues like double-free errors and dangling pointers. If you try to use the original variable after it has been moved, the compiler will produce an error.

  4. Borrowing as an Alternative: If you need to use the String after the function call, you can pass a reference to the String instead of moving it. This is known as borrowing.

    rust Copy
    fn borrows_string(some_string: &String) {
        println!("{}", some_string);
    }
    
    fn main() {
        let s = String::from("hello");
        borrows_string(&s);
        println!("{}", s); // This is valid because `s` was borrowed, not moved.
    }
  5. Mutable Borrowing: If the function needs to modify the String, you can pass a mutable reference.

    rust Copy
    fn modifies_string(some_string: &mut String) {
        some_string.push_str...
junior

junior

Gợi ý câu hỏi phỏng vấn

expert

When should I use Box , Arc , Rc , Cell , RefCell , RwLock and Mutex ?

middle

Explain the concept of Ownership in Rust. Why do we need it in Rust?

junior

What’s a closure in Rust?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào