Return first item of vector

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();

Which of course fails with:

error: missing lifetime specifier [E0106]

Is there any way to make this work?


Not in its current state.. no.

Basically, when first() returns here, v is dropped. Which makes returning a reference out of the function unsafe, because now the reference points into a void.

One option is to pass the vector in and return a reference to the first item out:

fn main () {
    let v = vec![1,2,3,4];

    println!("{:?}", first(&v).unwrap()); // Prints 1

fn first<T>(v: &Vec<T>) -> Option<&T> {

This seems redundant though and so without knowing exactly what you’re trying to do this seems like an okay option.

If you expand your question I will expand my answer.

Source : Link , Question Author : jgillich , Answer Author : Simon Whitehead

Leave a Comment