Reuse An Iterator With by_ref

by_ref borrows an iterator so take or filter adapters advance it a bounded amount, leaving the underlying iterator usable for later passes.

RustCli Tooling

Code

rustsnippet
16 lines
fn main() {
    let scores = vec![88, 42, 95, 67, 73, 91];
    let mut iter = scores.iter();

    // by_ref 借出可变引用:take 只推进 2 步,适配结束后 iter 原封不动
    let head: Vec<_> = iter.by_ref().take(2).collect();
    println!("head: {:?}", head);

    // 没有 by_ref 的话 take 会把迭代器整个消费掉,后面就拿不到剩余元素
    let middle: Vec<_> = iter.by_ref().take(2).collect();
    println!("middle: {:?}", middle);

    // 最后一次才真正耗尽
    let tail: Vec<_> = iter.collect();
    println!("tail: {:?}", tail);
}

How it works

Reuse An Iterator With by_ref comes down to the function main.

Putting it to use

Running the file prints labeled results such as head:, middle:, tail: — each operation’s effect is visible in the output.

Core lines

let middle: Vec<_> = iter.by_ref().take(2).collect();
let head: Vec<_> = iter.by_ref().take(2).collect();
let tail: Vec<_> = iter.collect();

Interactive Tools for This Topic

FAQ

What does Reuse An Iterator With by_ref print when run?
Invoke the file as-is — the `head:`, `middle:`, `tail:` prefixes identify which step printed each line.