I'm trying to write a shorthand function that returns the first element of a vector:
pub fn first() -> Option<&T> {
let v = Vec::new();
v.first()
}
Which of course fails with:
error: missing lifetime specifier [E0106]
Is there any way to make this work?
vector::front() This function can be used to fetch the first element of a vector container.
std::vector::front Returns a reference to the first element in the vector. Unlike member vector::begin, which returns an iterator to this same element, this function returns a direct reference.
To get the first element of a vector, we could do the following. In R, array indexes start at 1 - the 1st element is at index 1. This is different than 0-based languages like C, Python, or Java where the first element is at index 0. Notice that for the second example, we put a function inside the square brackets.
To take first element without copy:
vec.into_iter().nth(0)
But it will destroy a vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With