Vec first And last Handle Empty Slices

Read boundary elements through first and last instead of indexing, so an empty Vec yields None rather than a panic, and mutable variants edit in place.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    let mut values = vec![10, 20, 30];

    // first/last 返回 Option:空 Vec 得到 None,不会下标越界
    println!("first: {:?}, last: {:?}", values.first(), values.last());

    // 可变版本取得 &mut T,就地修改边界值
    if let Some(head) = values.first_mut() {
        *head += 5;
    }
    if let Some(tail) = values.last_mut() {
        *tail += 5;
    }
    println!("after mutation: {:?}", values);

    // 清空后仍安全:None 走 match 分支
    values.clear();
    match values.first() {
        Some(v) => println!("head still: {}", v),
        None => println!("empty vec: no head"),
    }
    println!("last on empty: {:?}", values.last());
}

What runs, in order

The snippet is organized around the function main.

A match spells out every case; omit one and the code does not compile.

Points of care

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

The API shape at the top: fn main()

Output lines are prefixed (first:, after mutation:, head still:), so every step’s outcome has its own line.

Quoted highlights

if let Some(head) = values.first_mut() {
    *head += 5;
}
if let Some(tail) = values.last_mut() {
    *tail += 5;
}
match values.first() {
    Some(v) => println!("head still: {}", v),
    None => println!("empty vec: no head"),
}

Interactive Tools for This Topic

FAQ

What does Vec first And last Handle Empty Slices print when run?
Execute the whole file; each printed line is prefixed with a label like `first:`, `after mutation:`, `head still:`.