split_last Tail Head Recursion

Take the last element plus the front slice with split_last, and its mirrored split_first, to write recursive slice walkers without index math.

RustData Integrity

Code

rustsnippet
36 lines
fn sum(values: &[u64]) -> u64 {
    // split_last:(&[..last], &last)。空切片返回 None,不必手写边界判断
    match values.split_last() {
        Some((rest, last)) => last + sum(rest),
        None => 0,
    }
}

fn first_word(input: &str) -> &str {
    // as_bytes() 走 u8 视图:' ' 是单字节 ASCII,按字节定位首个空格是安全的
    match input.as_bytes().iter().position(|&b| b == b' ') {
        Some(i) => &input[..i],
        None => input,
    }
}

fn main() {
    let readings = [3u64, 9, 4, 7];
    println!("sum: {}", sum(&readings));
    println!("empty sum: {}", sum(&[]));

    // 直接拆出尾部元素:tuple (rest, last) 顺序固定
    let (front, last) = readings.split_last().unwrap();
    println!("front {front:?} last {last}");

    // 镜像操作:头部元素与其余部分
    let (head, tail) = readings.split_first().unwrap();
    println!("head {head} tail {tail:?}");

    // 单元素切片:front 为空、last 是唯一元素
    let (f, l) = [42u64].split_last().unwrap();
    println!("single: front {:?} last {l}", f);

    // 字符串按字节切片:' ' 是单字节 ASCII,split_first 拆的是 u8
    println!("first word: {:?}", first_word("deploy notes v2"));
}

Recursion on slice ends

split_last Tail Head Recursion keeps everything in the functions sum, first_word and main.

sum walks the slice from the tail: each call takes the last element and recurses on rest, and the empty-slice None arm is the base case that returns 0.

first_word stays on the byte view: input.as_bytes().iter().position(|&b| b == b' ') finds the first space, Some(i) slices &input[..i], and the None arm returns the whole input when there is no space at all.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • The first_word call on "deploy notes v2" prints first word: "deploy" — the slice ends right before the first space byte.

Putting it to use

Entry signature: fn sum(values: &[u64]) -> u64

Every stage labels its own line (sum:, empty sum:, front), so the recursion and its boundary cases stay traceable.

Running the file executes main, which drives sum and first_word in order: the printed lines are sum: 23, empty sum: 0, the front/last pair, the head/tail pair, the single-element case, and first word: "deploy".

The tuple shapes to remember

let (front, last) = readings.split_last().unwrap();
let (head, tail) = readings.split_first().unwrap();
let (f, l) = [42u64].split_last().unwrap();

Interactive Tools for This Topic

FAQ

What does split_last Tail Head Recursion print when run?
Run it as a complete program — the output lines carry labels such as `sum:`, `empty sum:`, `front`.