实现说明
函数 total、max_of、main承载主要行为。
使用要点
- 每一步打印都带着自己的标签:
vec total:、array total:、range total:。 - 执行文件,
main会按顺序走完total、max_of。
常见问题
运行「函数边界收 IntoIterator」会打印什么?
运行文件本身,vec total:、array total:、range total: 这些前缀各对应一段演示逻辑。
签名一览:fn total(items: impl IntoIterator<Item = u32>) -> u32
核心语句
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()
}
代码示例
// 函数边界(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));
}