【发布时间】:2019-11-30 10:35:46
【问题描述】:
我有一个整数Vec,我想创建一个新的Vec,其中包含这些整数和这些整数的平方。我可以强制执行:
let v = vec![1, 2, 3];
let mut new_v = Vec::new(); // new instead of with_capacity for simplicity sake.
for &x in v.iter() {
new_v.push(x);
new_v.push(x * x);
}
println!("{:?}", new_v);
但我想使用迭代器。我想出了这段代码:
let v = vec![1, 2, 3];
let new_v: Vec<_> = v.iter()
.flat_map(|&x| vec![x, x * x])
.collect();
println!("{:?}", new_v);
但它在flat_map 函数中分配了一个中间Vec。
如何在没有分配的情况下使用flat_map?
【问题讨论】:
标签: rust iterator declarative