Rust Function: Getting Vector length
Write a Rust function that takes ownership of a vector and returns its length.
Sample Solution:
Rust Code:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics