Head And Tail Walks With split_first
Peel a borrowed head plus the remaining slice with split_first to walk sequences without copying or index arithmetic.
Code
fn main() {
let hops = [3, 9, 4, 12];
// split_first 借走头部并返回余下切片:不拷贝、不做下标算术
match hops.split_first() {
Some((first, rest)) => println!("first: {first}, rest: {rest:?}"),
None => println!("empty path"),
}
// while let 逐段走完整个序列(head/tail walk)
let mut remaining: &[u32] = &hops;
let mut total = 0;
while let Some((head, rest)) = remaining.split_first() {
total += head;
remaining = rest;
}
println!("total: {total}");
let empty: [u32; 0] = [];
assert!(empty.split_first().is_none());
println!("empty slice yields None");
}How it works
Head And Tail Walks With split_first comes down to the function main.
The file repeats itself only inside while let Some((head, rest)) = remaining.split_first(). The match expression is exhaustive — the compiler enforces that no case is missing.
What to watch for
- The dependency list is empty; the language runtime covers it all.
Using it
The main signature reads fn main()
Running the file prints labeled results such as first:, empty path, total: — each operation’s effect is visible in the output.
Key statements
while let Some((head, rest)) = remaining.split_first() {
total += head;
remaining = rest;
}
match hops.split_first() {
Some((first, rest)) => println!("first: {first}, rest: {rest:?}"),
None => println!("empty path"),
}
Interactive Tools for This Topic
FAQ
- What does Head And Tail Walks With split_first print when run?
- Invoke the file as-is — the `first:`, `empty path`, `total:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.