w3resource

Rust Function: Borrow Vector, Get first element

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

Write a Rust function that borrows a vector and returns the first element.

Sample Solution:

Rust Code:

// Define a function named 'get_first_element' that borrows a vector and returns the first element
fn get_first_element(v: &[i32]) -> Option<&i32> {
    v.first() // Return an Option containing a reference to the first element of the vector, or None if the vector is empty
}

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

    // Call the 'get_first_element' function and pass a reference to 'my_vector' to borrow it
    match get_first_element(&my_vector) {
        Some(first_element) => {
            println!("First element of the vector: {}", first_element);
        }
        None => {
            println!("The vector is empty.");
        }
    }

    // 'my_vector' is still accessible here because we only borrowed it
    println!("Used 'my_vector' after borrowing: {:?}", my_vector);
}

Output:

First element of the vector: 1
Used 'my_vector' after borrowing: [1, 2, 3, 4, 5]

Explanation:

Here is a brief explanation of the above Rust code:

  • fn get_first_element(v: &[i32]) -> Option<&i32> { ... }: This is a function named get_first_element that borrows a slice of a vector (&[i32]) and returns an Option<&i32>. The function returns 'Some' containing a reference to the first element of the vector if it exists, or 'None' if the vector is empty. The parameter 'v' is of type &[i32], indicating borrowing.
  • Inside the function:
    • We use the "first()" method to get an 'Option' containing a reference to the first element of the vector, or 'None' if the vector is empty.
  • In the main function,
    • We define a vector named 'my_vector'.
    • We then call the "get_first_element()" function and pass a reference to 'my_vector' (&my_vector) to borrow it.
    • We match on the result:
      • If 'Some', we print the value of the first element.
      • If 'None', we print a message indicating that the vector is empty.
    • 'my_vector' remains accessible after borrowing because we only borrowed it and didn't transfer ownership.

Rust Code Editor:

Previous: Rust Function: Getting Vector length.
Next: Rust Function: Take Tuple Ownership, Return element.

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://www.w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-4.php