w3resource

Rust Function: Double Vector length, Ownership transfer

Rust Ownership, Borrowing, and Lifetimes: Exercise-9 with Solution

Write a Rust function that takes ownership of a vector and returns a new vector with a doubled number of elements.

Sample Solution:

Rust Code:

// Define a function named 'double_vector_length' that takes ownership of a vector and returns a new vector with a doubled number of elements
fn double_vector_length(mut v: Vec<i32>) -> Vec<i32> {
    let cloned_v = v.clone(); // Create a clone of the vector to avoid immutably borrowing 'v'

    v.extend(cloned_v.iter().cloned()); // Double the number of elements in the vector by extending it with a clone of itself
    v // Return the new vector
} // Here 'v' goes out of scope and is dropped. Ownership is transferred to the function when called.
fn main() {
    let original_vector = vec![1, 2, 3]; // Define a vector

    // Call the 'double_vector_length' function and pass the ownership of 'original_vector' to it
    let new_vector = double_vector_length(original_vector);

    // Error! 'original_vector' is no longer accessible here because ownership was transferred to the function
    // println!("Attempt to use 'original_vector': {:?}", original_vector);

    // Print the new vector returned by the function
    println!("New vector with doubled length: {:?}", new_vector);
}

Output:

New vector with doubled length: [1, 2, 3, 1, 2, 3]

Explanation:

Here is a brief explanation of the above Rust code:

  • The function double_vector_length:
    • It takes ownership of a vector of integers (Vec<i32>) as its parameter.
    • Inside the function, a clone of the input vector is created using "clone()" method and assigned to 'cloned_v'. This is done to avoid immutably borrowing the original vector 'v'.
    • The elements of the cloned vector are then appended to the original vector using the "extend()" method. This effectively doubles the number of elements in the original vector.
    • Finally, the original vector 'v' is returned from the function.
  • The main function:
    • It defines an original vector named 'original_vector' containing the values [1, 2, 3].
    • The "double_vector_length()" function is called with 'original_vector' passed as an argument. Ownership of 'original_vector' is transferred to the function.
    • The resulting new vector with doubled length is assigned to 'new_vector'.
    • Attempting to use 'original_vector' after passing ownership to the function would result in a compilation error, as ownership has been moved.
    • The new vector 'new_vector' is printed using println!().

Rust Code Editor:

Previous: Rust Function: Borrow String Slice, Get first character.
Next: Rust Function: Borrowed integers sum.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-9.php