实现说明
Vec 三种迭代模式可以归结为函数 main。
本示例的循环部分是 for s in scores.iter_mut()。
使用要点
- 每一步打印都带着自己的标签:
total:、after bump:、doubled:。
常见问题
运行「Vec 三种迭代模式」会打印什么?
整个文件跑完,输出行以 total:、after bump:、doubled: 这类前缀开头。
核心语句
let doubled: Vec<i32> = scores.into_iter().map(|s| s * 2).collect();
let total: i32 = scores.iter().sum();
代码示例
fn main() {
let mut scores = vec![10, 20, 30];
// iter:&i32 只读借用,Vec 完好
let total: i32 = scores.iter().sum();
println!("total: {}", total);
// iter_mut:&mut i32 就地修改
for s in scores.iter_mut() {
*s += 1;
}
println!("after bump: {:?}", scores);
// into_iter:消耗 Vec,元素按值交付
let doubled: Vec<i32> = scores.into_iter().map(|s| s * 2).collect();
println!("doubled: {:?}", doubled);
// println!("{:?}", scores); // 已被消耗:编译错误
}