w3resource

Rust Function: Getting Vector length

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

Write a Rust function that takes ownership of a vector and returns its length.

Sample Solution:

Rust Code:

// Define a function named 'get_vector_length' that takes ownership of a vector and returns its length
fn get_vector_length(v: Vec) -> usize {
    let length = v.len(); // Get the length of the vector 'v'
    length // Return the length of the vector
} // Here 'v' goes out of scope and is dropped. Ownership is transferred to the function when called.

fn main() {
    let my_vector = vec![1, 2, 3, 4, 5]; // Define a vector

    // Call the 'get_vector_length' function and pass the ownership of 'my_vector' to it
    let vector_length = get_vector_length(my_vector);

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

    // Print the length of the vector returned by the function
    println!("Length of the vector: {}", vector_length);
}

Output:

Length of the vector: 5

Explanation:

Here is a brief explanation of the above Rust code:

  • fn get_vector_length(v: Vec<i32>) -> usize { ... }: This is a function named "get_vector_length()" that takes ownership of a 'Vec<i32>' as input and returns its length as a 'usize'. The parameter 'v' is of type 'Vec<i32>', indicating ownership transfer.
  • Inside the function:
    • Use the "len()" method to get the length of the vector 'v'.
    • Return the length of the vector.
  • In the main function,
    • Define a vector named "my_vector".
    • We then call the "get_vector_length()" function and pass the ownership of 'my_vector' to it. Ownership of 'my_vector' is transferred to the function, and 'my_vector' goes out of scope after the function call.
    • Attempting to use 'my_vector' after passing ownership to the function will result in a compilation error, as ownership has been moved.
    • We print the length of the vector returned by the function.

Rust Code Editor:

Previous: Rust Function: Print borrowed string.
Next: Rust Function: Borrow Vector, Get first element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.