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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.