Skip to content

slice::first

slice methods · Collections

Level: reference · for working programmers

One line: The first element as an Option<&T>None when the slice is empty, where v[0] would panic.

pub const fn first(&self) -> Option<&T>

Stable since 1.0.0; const since 1.56.0.

v[0] asserts there is a first element and panics if there is not. v.first() asks, and hands back None on an empty slice. That is the whole method, and it is the shape of every _mut, last, and get beside it.

It borrows: the Some holds a &T, the slice is untouched, and the reference cannot outlive the slice. To take the element out, use Vec::remove(0) (O(n), keeps order) or swap_remove(0) (O(1), does not). To get the first element and the rest, split_first returns Option<(&T, &[T])>.

Example

slice_first.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let nums = [10, 20, 30];
    let empty: [i32; 0] = [];
    println!("{:?} {:?}", nums.first(), empty.first());

    // nums[0] asserts; first() asks.
    if let Some(x) = nums.first() {
        println!("first is {x}");
    }
    // empty[0] would panic here: index out of bounds.

    // It borrows: x is a &i32 and nums is unchanged.
    let doubled = nums.first().map(|x| x * 2);
    println!("{doubled:?} {nums:?}");

    // Head and tail in one call.
    if let Some((head, tail)) = nums.split_first() {
        println!("head {head}, tail {tail:?}");
    }
}

Verified output of slice_first.rs — regenerated by tools/run_examples.py, never hand-typed.

Some(10) None
first is 10
Some(20) [10, 20, 30]
head 10, tail [20, 30]

See also

slice::first in the standard library ↗