Accept IntoIterator At Function Boundaries
Take impl IntoIterator at function boundaries so callers pass vectors, arrays, or ranges directly, and the function only needs into_iter and sum.
Code
// 函数边界(function boundaries)收 IntoIterator:
// Vec、数组、range 都能传进来,函数内部只依赖 into_iter
fn total(items: impl IntoIterator<Item = u32>) -> u32 {
items.into_iter().sum()
}
// 引用迭代用 Item = &u32 的 IntoIterator,读而不夺所有权
fn max_of<'a>(items: impl IntoIterator<Item = &'a u32>) -> Option<u32> {
items.into_iter().copied().max()
}
fn main() {
let vec = vec![3u32, 9, 4];
let array = [3u32, 9, 4];
let range = 3u32..=4;
println!("vec total: {}", total(vec.iter().copied()));
println!("array total: {}", total(array));
println!("range total: {}", total(range));
println!("max of vec refs: {:?}", max_of(&vec));
println!("max of array refs: {:?}", max_of(&array));
}How the snippet works
Count the functions total, max_of and main as the entire surface area of Accept IntoIterator At Function Boundaries.
Applying it
Signature: fn total(items: impl IntoIterator<Item = u32>) -> u32
The demo output is labeled (vec total:, array total:, range total:), so every printed line maps back to its originating operation.
The demo flow inside main is total and max_of — run the file to see it end to end.
Statements that matter
fn max_of<'a>(items: impl IntoIterator<Item = &'a u32>) -> Option<u32> {
items.into_iter().copied().max()
}
fn total(items: impl IntoIterator<Item = u32>) -> u32 {
items.into_iter().sum()
}
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Accept IntoIterator At Function Boundaries print when run?
- Execute the whole file; each printed line is prefixed with a label like `vec total:`, `array total:`, `range total:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.