Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first item of vector

Tags:

rust

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?

like image 982
jgillich Avatar asked Apr 26 '16 22:04

jgillich


People also ask

How do I find the first element of a vector?

vector::front() This function can be used to fetch the first element of a vector container.

Which function returns a reference to the first element in a vector?

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.

How do I get the first element of a vector in R?

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.


1 Answers

To take first element without copy:

vec.into_iter().nth(0)

But it will destroy a vector.

like image 129
Stanislav Sagan Avatar answered Nov 02 '22 06:11

Stanislav Sagan